[英]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.如何使用 C# 或 LINQ 读取“m:properties”后代。 This xml string is stored in variable of type XElement
此 xml 字符串存储在 XElement 类型的变量中
You can use combination of XNamespace
+ "element local name"
to reference element in namespace, for example :您可以使用
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();
I think this could show you how to use Linq to XML我认为这可以向您展示如何使用 Linq to XML
read the data from XML Structure using c# 使用 c# 从 XML 结构中读取数据
If anything else makes problems, just debug a little, see what you get from L2X operation, and move a step deeper trough data tree.如果还有其他问题,只需稍微调试一下,看看你从 L2X 操作中得到了什么,并通过数据树更深入一步。
Using Linq2XML使用 Linq2XML
var xDoc = XDocument.Load(filename);
var dict = xDoc.Descendants("m:properties")
.First()
.Attributes()
.ToDictionary(x => x.Name, x => x.Value);
Setup namespace manager.设置命名空间管理器。 Note that .net library does not support default namespace, so I added prefix "ns" to default namespace.
请注意,.net 库不支持默认命名空间,因此我在默认命名空间中添加了前缀“ns”。
use xpath or linq to query xml.使用 xpath 或 linq 查询 xml。 Following example uses xpath.
以下示例使用 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.