Reputation: 654
I have an xml flow wit h this structure :
<TagNames>
<TagName id="A1">some text...</TagName>
<TagName id="A2">some text...</TagName>
<TagName id="An">some text...</TagName>
</TagNames>
What's the best way to get only one node by 'id' without looping the entire file ? Linq to Sql, Xpath... I am using C#
Thanks
Upvotes: 1
Views: 91
Reputation: 24826
In XPath this is immediate:
"/TagNames/TagName[@id='A1']"
You can use it with XMLDocument.SelectSingleNode of System.Xml:
XmlDocument doc = new XmlDocument();
doc.Load("input.xml");
XmlNode single_node;
XmlElement root = doc.DocumentElement;
single_node = root.SelectSingleNode("/TagNames/TagName[@id='A1']");
Console.WriteLine(single_node.OuterXml);
Upvotes: 2
Reputation: 52798
Using LinqToXml you can do:
var xml = @"<TagNames>
<TagName id=""A1"">some text...</TagName>
<TagName id=""A2"">some text...</TagName>
<TagName id=""An"">some text...</TagName>
</TagNames>";
var document = XDocument.Parse(xml);
var node =
document
.Root //The root node
.Elements("TagName") //all elements called TagName under the root.
.Where(element => element.Attribute("id").Value == "A1") //Node with an attribute called Id with the value "A1".
.Single(); //Only return 1 element.
Upvotes: 2