简体   繁体   中英

How to retrieve the value of an element within an element in XML

I have the following 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 x.Name.LocalName == "Site"

Then my text contains <Site Address="0" Connect="COM1,9600"></Site>

What do I need to do to get the value of 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM