[英]XML get value from nextNode
I am trying to get a value from a node after my selected node. 我正在尝试从选定节点之后的节点获取值。 So far I have been able to get the whole node info as a var but I am stuck on how to get only the value out.
到目前为止,我已经能够以var的形式获取整个节点的信息,但是我仍然只限于如何获取值。
my xml looks like so 我的xml看起来像这样
<COLUMN>
<NAME>Addr1</NAME>
<VALUE>1234 my street</VALUE>
</COLUMN>
and I getting the node like this 我得到这样的节点
var address = (from c in contactInfo.Descendants("NAME")
where c.Value == "Addr1"
select c.NextNode).Single();
Thanks 谢谢
尝试:
(address as XElement).Value
NextNode
returns an XNode
, while you need an XElement
: 当您需要
XElement
, NextNode
返回一个XNode
:
var address = (from c in doc.Descendants("NAME")
where c.Value == "Addr1"
select c.NextNode).OfType<XElement>().Single().Value;
I would rather avoid putting it all on one line and do something like the following to add some extra checks: 我宁愿避免将它们全部放在一行上,并执行以下类似操作以添加一些额外的检查:
var address = (from c in doc.Descendants("NAME")
where c.Value == "Addr1"
select c.NextNode).Single();
var element = address as XElement;
if (element != null) {
string value = element.Value;
}
var node = contactInfo.Descendants("COLUMN")
.SingleOrDefault(c => c.Element("NAME").Value.Equals("Addr1"))
if (node != null)
var result = node.Element("VALUE").Value;
You should select COLUMN
element instead of searching for NAME
elements: 您应该选择
COLUMN
元素,而不要搜索NAME
元素:
var address = (from c in contactInfo.Descendants("COLUMN")
where (string)c.Element("NAME") == "Addr1"
select (string)c.Element("VALUE")).Single();
Same with method syntax: 与方法语法相同:
var address = contactInfo.Descendants("COLUMN")
.Where(c => (string)c.Element("NAME") == "Addr1")
.Select(c => (string)c.Element("VALUE"))
.Single();
Also you should be completely sure that there always exist exactly one column element with name Addr1
. 另外,您应该完全确保始终存在一个名称为
Addr1
列元素。 Otherwise Single()
will throw an exception. 否则,
Single()
将引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.