2010-01-27 19 views
2

在这里,我有XML:我的XPath有什么问题?

<root> 
    <field ...>offer</field> 
    <field type="ferrari" ...>car</field> 
    <field ...>company</field> 
    <field ...>whatever</field> 
</root> 

,我想知道«汽车»的«类型»通过提取的元素。我想是这样的:

/root[field='car']/field (or /root[field='car']) 

已经足够了,但是当我试图执行我的C#代码:

XmlDocument document = new XmlDocument(); 
document.InnerXml = "..."; // xml of above 
XmlNode node = document.DocumentElement.SelectSingleNode("... xpath of above ..."); 

对象«节点»它总是包含的第一个子元素«现场»(中提供)并且在SelectNodes(“... same xpath ...”)的情况下返回所有元素«field»忽略条件。

有什么问题? XPath错了?

+0

你的XML似乎倒退。不应该类型=“汽车”和元素的价值是法拉利? – 2010-01-27 18:26:00

+0

那么我不得不对这种XML做解析器,我不能改变它的结构,因为这是客户的定义。但我同意你这样的结构有点畸形... – Alexian 2010-01-28 14:19:31

回答

2
/root/field[text()='car']/@type 

将带回表示文本值为“car”的元素“字段”的属性“类型”的节点。这个XmlNode的值将是“ferrari”。

/root/field[text()='car'] 

将带回代表元素“场”(其文本值是“车”),您可以以编程方式获得的类型属性的节点:

XmlNode fieldNode = document.DocumentElement.SelectSingleNode(@"/root/field[text()='car']"); 
string type = fieldNode.Attributes["type"].Value; 
//type == "ferrari" 
+0

谢谢你! :)我不知道我必须指定内部内容必须转向文本! BR! – Alexian 2010-01-27 16:59:36