Reputation: 4781
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>
Upvotes: 1
Views: 332
Reputation: 13394
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
Upvotes: 0
Reputation: 26213
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());
Upvotes: 2
Reputation: 899
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 "";
}
}
Upvotes: 2