简体   繁体   中英

Reading nested element of an XML document in C#

I have an XML document that I get from a webservice. I need to be able to read the nested elements of the floorCapacity into an array.

This is a sample of the XML document

<?xml version="1.0" encoding="utf-8"?>
<BuildingCapacity xmlns="http://www.somenamespace.com/CapacityWebService/">
    <time>2021-04-14T12:24:14.440Z</time>
    <siteId>1001</siteId>
    <site>Main Site</site>
    <loc>Building 1</loc>
    <floors></floors>
    <floorCapacity>
        <int>381</int>
        <int>166</int>
        <int>220</int>
        <int>45</int>
    </floorCapacity>
</BuildingCapacity>

And this is the code I'm trying to get to work.

    XDocument captureDoc = XDocument.Parse(message);
    XNamespace ns = "http://www.somenamespace.com/CapacityWebService/";

    string time = captureDoc.Root.Element(ns + "time").Value;
    string locSiteId = captureDoc.Root.Element(ns + "siteId").Value;
    string locSite = captureDoc.Root.Element(ns + "site").Value;
    string loc = captureDoc.Root.Element(ns + "loc").Value;

    int floors = int.Parse(captureDoc.Root.Element(ns + "floors").Value);
    int[] floorCapacity = new int[floors];
    int floor = 0;

    foreach (XElement floorCap in captureDoc.Root.Elements(ns + "floorCapacity"))
    {
        floorCapacity[floor] = int.Parse(floorCap.Element(ns + "int").Value);
        floor++;
    }

The problem is that the foreach loop only loops once and not four times as I would expect.

Can anyone offer any pointers how I get to the values of the data in the floorCapacity element please?

The captureDoc.Root.Elements(ns + "floorCapacity") loop through the elements floorCapacity the only one.
You should loop through floorCap.Elements(ns + "int")

There is a better way, ie LINQ way, to get an int array from XML without any looping in one single statement.

c#

void Main()
{
    XDocument captureDoc = XDocument.Parse(@"<BuildingCapacity xmlns='http://www.somenamespace.com/CapacityWebService/'>
        <time>2021-04-14T12:24:14.440Z</time>
        <siteId>1001</siteId>
        <site>Main Site</site>
        <loc>Building 1</loc>
        <floors></floors>
        <floorCapacity>
            <int>381</int>
            <int>166</int>
            <int>220</int>
            <int>45</int>
        </floorCapacity>
    </BuildingCapacity>");

    XNamespace ns  = captureDoc.Root.GetDefaultNamespace();
    
    int[] floorCapacity = captureDoc.Descendants(ns + "floorCapacity")
        .SelectMany(x => x.Elements(ns + "int"))
        .FirstOrDefault().Value
        .Select(s => int.Parse(s.ToString()))
        .ToArray();
}

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