开发者

How to quickly reach a subchild in XML?

开发者 https://www.devze.com 2023-01-13 01:24 出处:网络
I have an XML file full of this: <machine id=\"\"> <application id=\"\"> <fichier name=\"\"/>

I have an XML file full of this:

 <machine id="">
  <application id="">
   <fichier name=""/>
   <fichier name=""/>
   <fichier name=""/>
  </application>
  <application id="">
   <fichier name=""/>
   <fichier name=""/>
   <fichier name=""/>
  </application>
 </machine>

I know the id of machine and application and the name of fichier. Ri开发者_如何学Cght now, I scan all machine, then once found, scan application and once found, scan fichier. Rather long, so how can I quickly reach the fichier I want?


something like the following should work, assuming you loaded your XML in an XmlDocument called xmlDoc:

// 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: the above uses XPath, there are several tutorials on the Net (as mentioned by another user meanwhile), but if you really want to learn how to work with it, try some of Jenni Tennison's books on XSLT, she's an excellent explainer.


XPath

http://www.w3schools.com/XPath/xpath_syntax.asp


You could do this with LINQ to XML like this:

 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号