简体   繁体   中英

Reading child nodes from xml string using C#, LINQ

- <entry xml:base="http://testserver.windows.net/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" m:etag="W/"datetime'2015-08-30T00%3A04%3A02.9193525Z'"">
  <id>http://testserver.windows.net/Players(PartitionKey='zzz',RowKey='000125')</id> 
  <category term="testServer.Players" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" /> 
  <link rel="edit" title="Players" href="Players(PartitionKey='zzz',RowKey='000125')" /> 
  <title /> 
  <updated>2014-04-30T00:53:42Z</updated> 
- <author>
  <name /> 
  </author>
- <content type="application/xml">
- <m:properties>
  <d:PartitionKey>zzz</d:PartitionKey> 
  <d:RowKey>000125</d:RowKey> 
  <d:Timestamp m:type="Edm.DateTime">2014-04-30T00:04:02.9193525Z</d:Timestamp> 
  <d:Name>Black color</d:Name> 
  <d:Comments>Test comments</d:Comments> 
  </m:properties>
  </content>
  </entry>

How can I read "m:properties" descendants using C# or LINQ. This xml string is stored in variable of type XElement

You can use combination of XNamespace + "element local name" to reference element in namespace, for example :

XElement myxelement = XElement.Parse("your XML string here");
XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
List<XElement> properties = myxelement.Descendants(m+"properties").ToList();

I think this could show you how to use Linq to XML

read the data from XML Structure using c#

If anything else makes problems, just debug a little, see what you get from L2X operation, and move a step deeper trough data tree.

Using Linq2XML

var xDoc = XDocument.Load(filename);
var dict = xDoc.Descendants("m:properties")
           .First()
           .Attributes()
           .ToDictionary(x => x.Name, x => x.Value);
  1. Setup namespace manager. Note that .net library does not support default namespace, so I added prefix "ns" to default namespace.

  2. use xpath or linq to query xml. Following example uses xpath.

     XmlNamespaceManager NamespaceManager = new XmlNamespaceManager(new NameTable()); NamespaceManager.AddNamespace("base", "http://testserver.windows.net/"); NamespaceManager.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices"); NamespaceManager.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"); NamespaceManager.AddNamespace("ns", "http://www.w3.org/2005/Atom"); XDocument doc = XDocument.Parse(XElement); var properties = doc.XPathSelectElement("/ns:entry/ns:content/m:properties", NamespaceManager);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM