开发者

Found a node with ID

I have an xml flow wit h this structure :

<TagNames>
  <TagName id="A1">some text...</TagName>
  <TagName id="A2">some text...</TagName>
  &开发者_C百科lt;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


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);


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜