C# 如何快速接触XML中的子孩子?
我有一个包含以下内容的XML文件:C# 如何快速接触XML中的子孩子?,c#,xml,winforms,C#,Xml,Winforms,我有一个包含以下内容的XML文件: <machine id=""> <application id=""> <fichier name=""/> <fichier name=""/> <fichier name=""/> </application> <application id=""> <fichier name=""/> <fichier nam
<machine id="">
<application id="">
<fichier name=""/>
<fichier name=""/>
<fichier name=""/>
</application>
<application id="">
<fichier name=""/>
<fichier name=""/>
<fichier name=""/>
</application>
</machine>
我知道机器和应用程序的id以及fichier的名字。现在,我扫描所有的机器,然后一旦找到,扫描应用程序,一旦找到,扫描fichier。相当长的时间,那么我如何快速到达我想要的fichier呢?XPath
假设您将XML加载到名为
xmlDoc
的XmlDocument
中,那么类似于以下内容的内容应该可以工作:
// load your XML (you may already have this)
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(pathToYourXML);
// construct your XPath
string formattedXPath = string.Format(
"/machine[@id='{0}']/application[@id='{1}']/fichier[@name='{2}']",
machineId,
applicationId,
fichierName);
// select your node
XmlElement elementFichier = (XmlElement) xmlDoc.SelectSingleNode(formattedXPath)
// if you need the text from this child, use this (text itself is a child node):
string text = elementFichier.FirstChild.Value;
PS:上面使用的是XPath,网上有几个教程(另一位用户同时提到),但是如果您真的想学习如何使用它,请尝试一些Jenni Tennison关于XSLT的书,她是一位出色的解释者。您可以使用LINQ to XML这样做:
var result = from m in xml.Descendants("machine")
where m.Attribute("id").Value == "1"
let a = m.Elements("application").Where (x => x.Attribute("id").Value == "3")
let f = a.Elements("fichier").Where (x => x.Attribute("name").Value == "b")
select f;
出于某种原因,这并没有给我任何回报。我在xmldoc上得到空返回。SelectSingleNode@Wildhorn:如果您得到
null
,则可能是您的输入不同(即,根不是/machine
,请用根的正确路径替换它,或者使用/
而不是/
),或者您的翻译中有打字错误,因为上面的代码与您的输入不一致(添加属性值),为我生成一个节点…是的,我想我错放了一个“=”。只是一个愚蠢的输入错误:)