代码之家  ›  专栏  ›  技术社区  ›  Wildhorn

如何在XML中快速到达子类?

  •  1
  • Wildhorn  · 技术社区  · 15 年前

    我有一个XML文件,其中包含:

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

    我知道机器和应用程序的ID以及fichier的名称。现在,我扫描所有机器,然后一旦找到,扫描应用程序,一旦找到,扫描fichier。相当长的时间,那么我怎样才能快速到达我想要的榕树?

    3 回复  |  直到 15 年前
        1
  •  1
  •   Sruly    15 年前
        2
  •  2
  •   Abel    15 年前

    假设将XML加载到 XmlDocument 打电话 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;
    

    附言:上面使用的是xpath,网上有很多教程(另一个用户同时提到),但是如果你真的想学习如何使用它,可以试试Jenni Tennison的一些关于xslt的书,她是一个很好的解释者。

        3
  •  0
  •   Steve Michelotti    15 年前

    您可以这样使用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;