Find values under one node in XML

后端 未结 2 1888
执笔经年
执笔经年 2021-01-28 10:47

Below is xml file format from which words to be searched.



Preface


             


        
相关标签:
2条回答
  • 2021-01-28 11:26

    It is not possible theoretically. The reason is that XML/XPATH does not ensure order as the result of a query is a "node-set" which by definition is "an unordered collection of nodes without duplicates".

    http://www.w3.org/TR/xpath/

    Nevertheless, you can get close to the requirement. For example, you can get the first word:

    XmlDocument objXmlDoc = new XmlDocument();
    XmlNodeList objXmlNodeList;
    objXmlDoc.Load(sFilePath);
    objXmlNodeList = objXmlDoc.SelectNodes("//Word");
    string s = string.Empty;
    XmlNodeList wordNodes = objXmlNodeList[0].ChildNodes;
    foreach (XmlNode characterNode in wordNodes)
    {
       s = s + characterNode.InnerText;
    }
    
    0 讨论(0)
  • 2021-01-28 11:46

    I would use Linq2Xml

    XDocument xDoc = XDocument.Parse(xml); //or XDocument.Load(fileName)
    var words = xDoc.Descendants("Word")
                    .Select(w => String.Join("",w.Descendants("Char").Select(c => c.Value)))
                    .ToList();
    

    --EDIT--

    for @Y.Ecarri

    var words2 = xDoc.XPathSelectElements("//Word")
                     .Select(w => String.Join("", w.Elements().Select(c => c.Value)))
                     .ToList();
    
    0 讨论(0)
提交回复
热议问题