How can I get a node by id in XML?

后端 未结 2 1410
孤独总比滥情好
孤独总比滥情好 2020-12-20 01:26

I am creating a language translation using XML by id

XML:



    Word         


        
2条回答
  •  星月不相逢
    2020-12-20 01:34

    I suggest you to use LINQ to XML for parsing XML. It has nice strongly typed API. Getting string word by integer id looks like (requires System.Xml.Linq namespace):

    var xdoc = XDocument.Load(filePath);
    string word = xdoc.Root.Elements()
                      .Where(w => (int)w.Attribute("id") == id)
                      .Select(w => (string)w)
                      .FirstOrDefault();
    

    Or even less code with XPath (requires System.Xml.XPath namespace):

    string word = (string)xdoc.XPathSelectElement("//word[@id='10001']");
    

提交回复
热议问题