簡體   English   中英

使用 C#、LINQ 從 xml 字符串中讀取子節點

[英]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>

如何使用 C# 或 LINQ 讀取“m:properties”后代。 此 xml 字符串存儲在 XElement 類型的變量中

您可以使用XNamespace + "element local name"來引用命名空間中的元素,例如:

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

我認為這可以向您展示如何使用 Linq to XML

使用 c# 從 XML 結構中讀取數據

如果還有其他問題,只需稍微調試一下,看看你從 L2X 操作中得到了什么,並通過數據樹更深入一步。

使用 Linq2XML

var xDoc = XDocument.Load(filename);
var dict = xDoc.Descendants("m:properties")
           .First()
           .Attributes()
           .ToDictionary(x => x.Name, x => x.Value);
  1. 設置命名空間管理器。 請注意,.net 庫不支持默認命名空間,因此我在默認命名空間中添加了前綴“ns”。

  2. 使用 xpath 或 linq 查詢 xml。 以下示例使用 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM