Finding element in XDocument?

前端 未结 7 1633
眼角桃花
眼角桃花 2020-12-02 20:02

I have a simple XML


  
    greatest Band
            


        
7条回答
  •  孤街浪徒
    2020-12-02 20:15

    My experience when working with large & complicated XML files is that sometimes neither Elements nor Descendants seem to work in retrieving a specific Element (and I still do not know why).

    In such cases, I found that a much safer option is to manually search for the Element, as described by the following MSDN post:

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/3d457c3b-292c-49e1-9fd4-9b6a950f9010/how-to-get-tag-name-of-xml-by-using-xdocument?forum=csharpgeneral

    In short, you can create a GetElement function:

    private XElement GetElement(XDocument doc,string elementName)
    {
        foreach (XNode node in doc.DescendantNodes())
        {
            if (node is XElement)
            {
                XElement element = (XElement)node;
                if (element.Name.LocalName.Equals(elementName))
                    return element;
            }
        }
        return null;
    }
    

    Which you can then call like this:

    XElement element = GetElement(doc,"Band");
    

    Note that this will return null if no matching element is found.

提交回复
热议问题