Lennart Stromberg
Lennart Stromberg

Reputation: 43

Read attribute from xml

Can someone help me read attribute ows_AZPersonnummer with asp.net using c# from this xml structure

<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>

And get value 196202081276.

Upvotes: 3

Views: 2569

Answers (4)

Kev
Kev

Reputation: 119806

The XmlNamespaceManager is your friend:

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);

You can also use 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;

Upvotes: 5

C&#233;dric Guillemette
C&#233;dric Guillemette

Reputation: 2408

Use <%# Eval("path to attribute") %> but you need to load the xml has a DataSource.

Otherwise you can load it using XmlTextReader. Here's an example.

Upvotes: 0

Welbog
Welbog

Reputation: 60418

Open this up in an XmlDocument object, then use the SelectNode function with the following XPath:

//*[local-name() = 'row']/@ows_AZPersonnummer

Basically, this looks for every element named "row", regardless of depth and namespace, and returns the ows_AZPersonnummer attribute of it. Should help avoid any namespace issues you might be having.

Upvotes: 6

Yuval
Yuval

Reputation: 8087

I'd say you need an XML parser, which I believe are common. This looks like a simple XML structure, so the handling code shouldn't be too hard.

Upvotes: 0

Related Questions