从xml读取属性

Len*_*erg 3 c# xml asp.net xml-attribute

有人可以帮我从这个xml结构中使用c#读取属性ows_AZPersonnummer

<listitems 
  xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" 
  xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" 
  xmlns:rs="urn:schemas-microsoft-com:rowset"
  xmlns:z="#RowsetSchema"
  xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<rs:data ItemCount="1">
   <z:row 
      ows_AZNamnUppdragsansvarig="Peter" 
      ows_AZTypAvUtbetalning="Arvode till privatperson" 
      ows_AZPersonnummer="196202081276"
      ows_AZPlusgiro="5456436534"
      ows_MetaInfo="1;#"
      ows__ModerationStatus="0"
      ows__Level="1" ows_ID="1"
      ows_owshiddenversion="6"
      ows_UniqueId="1;#{11E4AD4C-7931-46D8-80BB-7E482C605990}"
      ows_FSObjType="1;#0"
      ows_Created="2009-04-15T08:29:32Z"
      ows_FileRef="1;#uppdragsavtal/Lists/Uppdragsavtal/1_.000" 
    />
</rs:data>
</listitems>
Run Code Online (Sandbox Code Playgroud)

并获得价值196202081276.

Wel*_*bog 6

XmlDocument对象中打开它,然后使用SelectNode带有以下XPath 的函数:

//*[local-name() = 'row']/@ows_AZPersonnummer
Run Code Online (Sandbox Code Playgroud)

基本上,无论深度和名称空间如何,它都会查找名为"row"的每个元素,并返回ows_AZPersonnummer它的属性.应该有助于避免您可能遇到的任何名称空间问题.


Kev*_*Kev 5

XmlNamespaceManager的是你的朋友:

string xml = "..."; //your xml here
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

XmlNamespaceManager nsm = new XmlNamespaceManager(new NameTable());
nsm.AddNamespace("z", "#RowsetSchema");

XmlNode n = doc.DocumentElement
               .SelectSingleNode("//@ows_AZPersonnummer", nsm);
Console.WriteLine(n.Value);
Run Code Online (Sandbox Code Playgroud)

您还可以使用LINQ to XML:

XDocument xd = XDocument.Parse(xml);
XNamespace xns = "#RowsetSchema";
string result1 = xd.Descendants(xns + "row")
            .First()
            .Attribute("ows_AZPersonnummer")
            .Value;
// Or...

string result2 =
    (from el in xd.Descendants(xns + "row")
     select el).First().Attribute("ows_AZPersonnummer").Value;
Run Code Online (Sandbox Code Playgroud)

  • 我即将发布LINQ版本[result1版本],但你更快!唯一的区别是我使用.FirstOrDefault()而我最后没有.ToString()(因为.Value是一个字符串).result2版本不太正确. (2认同)