Reading child nodes from xml string using C#, LINQ

2019-08-06 19:11发布

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

4条回答
我只想做你的唯一
2楼-- · 2019-08-06 20:04

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.

查看更多
Juvenile、少年°
3楼-- · 2019-08-06 20:05

Using Linq2XML

var xDoc = XDocument.Load(filename);
var dict = xDoc.Descendants("m:properties")
           .First()
           .Attributes()
           .ToDictionary(x => x.Name, x => x.Value);
查看更多
我只想做你的唯一
4楼-- · 2019-08-06 20:10

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();
查看更多
叛逆
5楼-- · 2019-08-06 20:11
  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);
    
查看更多
登录 后发表回答