[英]Extracting specific nodes from an XML file
I want to read a section from the XML file below with C#. 我想使用C#从下面的XML文件中读取一节。
<?xml version="1.0" encoding="utf-8" >
<DataSet>
<xs:schema id="NewDataSet" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Table">
<xs:complexType>
<xs:sequence>
<xs:element name="Column1" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<NewDataSet>
<Table diffgr:id="Table1" msdata:rowOrder="0">
<Column1><Properties><Property>.....
I want to extract the nodes below the Column1
nodes. 我想提取
Column1
节点下面的节点。 The Properties
node has lots of Property
nodes, so I want the Properties
node with all the Property
nodes. “
Properties
节点具有很多“ Property
节点,因此我希望“ Properties
节点具有所有“ Property
节点。
Please let me know the easiest and efficient way to get the nodes in C#. 请让我知道用C#获取节点的最简单有效的方法。
You can use an Linq-to-XML classes to parse the string and then XPath expression to select the nodes that you want: 您可以使用Linq-to-XML类来解析字符串,然后使用XPath表达式来选择所需的节点:
XElement doc = XElement.Parse(s); //where s is a string containing the XML
var properties = doc.XPathSelectElements("//Column1/Properties");
Now properties
contains a enumerable of the nodes that you want. 现在,
properties
包含所需节点的枚举。
If you want to iterate through all the Property nodes you can do so like this: 如果要遍历所有“属性”节点,可以这样进行:
foreach(var pp in properties)
{
foreach(var p in pp.Elements("Property"))
{
//do something
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.