[英]how to take a specific child node value in xml using C#
I have an xml schema like below 我有一个如下的xml模式
<library>
<book>
<id>1</id>
<name>abc</name>
<read>
<data>yes</data>
<num>20</num>
</read>
</book>
<book>
<id>20</id>
<name>xyz</name>
<read>
<data>yes</data>
<num>32</num>
</read>
</book>
</library>
Now if the id
is 20
i need to take the value of tag <num>
under <read>
现在,如果
id
为20
我需要在<read>
下获取标记<num>
的值
I done the code as below 我完成了如下代码
var xmlStr = File.ReadAllText("e_test.xml");
var str = XElement.Parse(xmlStr);
var result = str.Elements("book").Where(x => x.Element("id").Value.Equals("20")).ToList();
this give the whole <book>
tag with id 20
. 这将给出ID为
20
的整个<book>
标签。 From this how can I extract only the value of tag <num>
. 从中我如何仅提取标记
<num>
的值。
ie is i need to get the value 32
in to a variable 即我是否需要将值
32
放入变量
Before you try to extract the num
value, you need to fix your Where
clause - at the moment you're comparing a string with an integer. 在尝试提取
num
值之前,需要修复Where
子句-目前正在将字符串与整数进行比较。 The simplest fix - if you know that your XML will always have an id
element which has a textual value which is an integer - is to cast the element to int
. 最简单的解决方法是将元素转换为
int
,如果您知道您的XML将始终具有一个id
元素,该id
元素的文本值为整数。
Next, I'd use SingleOrDefault
to make sure there's at most one such element, assuming that's what your XML document should have. 接下来,我将使用
SingleOrDefault
来确保最多有一个这样的元素,假设这就是您的XML文档应该具有的元素。
Then you just need to use Element
twice to navigate down via read
and then num
, and cast the result to int
again: 然后,您只需要使用
Element
两次,就可以先通过read
然后通过num
向下导航,并将结果再次转换为int
:
// Or use XDocument doc = ...; XElement book = doc.Root.Elements("book")...
XElement root = XElement.Load("e_test.xml")
XElement book = root.Elements("book")
.Where(x => (int) x.Element("id") == 20)
.SingleOrDefault();
if (book == null)
{
// No book with that ID
}
int num = (int) book.Element("read").Element("num");
If you're not dead set on using Linq, how about this XPath? 如果您还不习惯使用Linq,那么该XPath呢? XPath is probably more widely understood, and is really simple.
XPath可能被更广泛地理解,并且确实很简单。 The XPath to find your node would be:
查找节点的XPath将是:
/library/book[id=20]/read/num
Which you could use in C# thus: 您可以在C#中使用以下代码:
var doc = new XmlDocument();
doc.LoadXml(myString);
var id = 20;
var myPath = "/library/book[id=" + id + "]/read/num";
var myNode = doc.SelectSingleNode(myPath);
Then you can do whatever you like with myNode
to get its value etc.. 然后,您可以使用
myNode
进行任何myNode
以获取其值,等等。
Helpful reference: 有用的参考资料:
http://www.w3schools.com/xsl/xpath_syntax.asp http://www.w3schools.com/xsl/xpath_syntax.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.