简体   繁体   中英

Getting tag with specific name in XML using C#

I have XML file and I have parse it into XDocument. I need to get all tags with name <Entity> , but there is a one problem.

Tag <Entity> contains two more Entity tags as his children. (among with many others tag as well).

When I do this:

var entity= xmlDoc.Descendants().Where(x => x.Name.LocalName == "Entity");

I get them all of course.

Is there a way to tell: Get me all Entity tags, but not Entity tag that is child of an Entity tag?

Structure looks like this:

<Entity> --> I need to get this one
   <SomeTags>Value</SomeTags>
   <First>
     <Entity>Value</Entity> --> Skip this one
   </First>
   <Entity>Value<Entity> --> Skip this one as well
</Entity>

You could use the following:

private String path= @"C:\Temp\xml.xml"; //YOur XML path
public string getValue(string Name)
{
    try
    {
        doc = XDocument.Load(path);
        var dada = (from c in doc.Descendants(Name)
                    where c.Parent.Name!=Name
                    select c).First();
        return dada.Value;
    }
    catch (Exception)
    {
        global::System.Windows.Forms.MessageBox.Show("There was a problem with the XML");
        return "";
    }
}

Descendants gets all child elements recursively. Assuming the elements you want are all at the same depth, you need to find their parent element and query using Elements instead - this will only get the immediate children.

doc.Descendants("parent")
    .Elements("Entity");

If that doesn't work for your structure, you could also literally query as you've suggested - find all those Entity elements that don't have any parent Entity elements:

doc.Descendants("Entity")
    .Where(x => !x.Ancestors("Entity").Any());

Building on @CharlesMager's second example, this should be the correct syntax:

doc.Descendants("Entity").Where(x => !x.Ancestors("Entity").Any());

btw: one of your Entities isn't closed

Example on dotNetFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM