[英]How to retrieve the value of an element within an element in XML
I have the following XML: 我有以下XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Project>
<Site Address="0" Connect="COM1,9600">
</Site>
</Project>
I am trying to get the value of 'Connect' 我正在尝试获取“连接”的价值
I have this code: 我有以下代码:
var doc = XDocument.Load(xml);
var q = from x in doc.Root.Elements()
where x.Name.LocalName == "Connect"
select x;
ClientTB.Text = q.FirstOrDefault().ToString();
But when I run this I get the error Object reference not set to an instance of an object. 但是,当我运行此命令时,出现错误“对象引用未设置为对象实例”。
If I change the where statement to: 如果我将where语句更改为:
where x.Name.LocalName == "Site"
Then my text contains <Site Address="0" Connect="COM1,9600"></Site>
然后我的文本包含
<Site Address="0" Connect="COM1,9600"></Site>
What do I need to do to get the value of Connect? 我需要做什么才能获得Connect的价值?
var q = from x in doc.Root.Elements()
where x.Name.LocalName == "Site"
select x.Attribute("Connect");
Alternative 另类
var q = from x in doc.Descendants("Site").Attributes("Connect")
select x;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.