使用C#,LINQ从xml字符串中读取子节点
- http://testserver.windows.net/Players(PartitionKey='zzz',RowKey='000125') 2014-04-30T00:53:42Z - - - zzz 000125 2014-04-30T00:04:02.9193525Z Black color Test comments
如何使用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 properties = myxelement.Descendants(m+"properties").ToList();
我想这可以告诉你如何使用Linq到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);
-
设置命名空间管理 请注意.net库不支持默认命名空间,因此我在默认命名空间中添加了前缀“ns”。
-
使用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);