2015-11-13 81 views
0

我有一个XML文件,其中的一部分显示在下面。通过文本属性获取XML节点ID

<node id="413" text="plant1"> 
    <node id="419" text="Detail Reports"> 
    <node id="424" text="Bulk Lactol" reportid="14" nodetype="1"/> 
    <node id="427" text="Effluent" reportid="17" nodetype="1"/> 
    <node id="425" text="Pasteurisers" reportid="15" nodetype="1"/> 
    <node id="421" text="Tank 8" reportid="12" nodetype="1"/> 
    <node id="420" text="Tank 9" reportid="11" nodetype="1"/> 
    </node> 
    <node id="422" text="Summary Reports"> 
    <node id="423" text="plant1 Summary" reportid="13" nodetype="1"/> 
    <node id="426" text="Effluent Summary" reportid="16" nodetype="1"/> 
    </node> 
</node> 

我想通过'文本'值得到'节点ID'。 我尝试了以下。

string y = "Bulk Lactol" 
XmlDocument doc = new XmlDocument(); 
doc.Load("C:\\Users\\Joe\\Desktop\\wt.xml"); 
XmlNode node = doc.DocumentElement.SelectSingleNode(y); 
string x = Convert.ToString(node); 

但我得到一个异常:

'散装乳醇' 具有无效令牌。

我发现了一些类似的问题,但我对XML不是很熟悉,所以我在修改它们时遇到了问题,感谢您的帮助。

回答

3

SelectSingleNode and SelectNodes accept XPath string作为参数。

您可以使用以下XPath找到此文件:

string y = "Bulk Lactol"; 

XmlDocument doc = new XmlDocument(); 
doc.Load("C:\\Users\\Joe\\Desktop\\wt.xml"); 

XmlNode node = doc.SelectSingleNode(@"//node[@text='Bulk Lactol']"); 
string x = node.InnerText; 

//node[@text='Bulk Lactol']的XPath意味着

其中有一个属性“文本”与价值“散装乳醇”

层级中的任何元素
+0

不要忘记选择@id –