Home > Back-end >  Linq to XML - Get attribute and elements
Linq to XML - Get attribute and elements

Time:10-17

Given this XML, how can I get data for each outageEvent including both attributes and elements?

In the end, I need to move this data to a database, but doing this as a first step.

Desired end format is a 'row' for each outageEvent with the attribuite ObjectID and then the elements in outageEvent.

outageEvent
-------------
ObjectID
Comment
objectName
...etc.

Not necessary to get grandchildren of outageEvent such as ExtensionList children at this point.

So far I am working on querying with Linq to XML. I'm able to query and get the objectIDs. Separately, I am able to query to get all the elements. Trying to combine the two is giving me problems. Haven't done any C# in a while, so that is 99% of the problem.

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
    </soap:Header>
    <soap:Body>
        <OutageEventChangedNotification xmlns="http://www.multispeak.org/Version_4.1_Release">
            <oEvents>
                <outageEvent objectID="2021-10-16-0002">
                    <comments>Test outage 2</comments>
                    <extensionsList>
                        <extensionsItem>
                            <extName>primaryCrew</extName>
                            <extValue>Primary Crew Name</extValue>
                            <extType>string</extType>
                        </extensionsItem>
                    </extensionsList>
                    <objectName>Outage Name</objectName>
                    <!-- more elements -->
                </outageEvent>
                <outageEvent objectID="2021-10-16-0001">
                    <comments>Test outage 1</comments>
                    <!-- more elements -->
                </outageEvent>
            </oEvents>
        </OutageEventChangedNotification>
    </soap:Body>
</soap:Envelope>

C# code:

XElement outages = XElement.Parse(requestBody);
            XNamespace oecn = "http://www.multispeak.org/Version_4.1_Release";
//This works
            IEnumerable<string> outageIDs = from outage in outages.Descendants(oecn   "outageEvent")
                                                   select (string) outage.Attribute("objectID");

            foreach (string outageID in outageIDs)
            {
                Console.WriteLine($"IENUMBERABLE: {outageID}");
            }

//This works
            IEnumerable<string> outageProperties = from outage in outages.Descendants(oecn   "outageEvent")
                                                   select (string)outage;

            foreach (string outageProperty in outageProperties)
            {
                Console.WriteLine($"IENUMBERABLE: {outageProperty} \r\n");
            }

//This Doesn't
            var alloutages = from outage in outages.Descendants(oecn   "outageEvent")
                                  select new /*Error Here*/
                              {
                                  outageID = outage.Attribute("objectID").Value,
                                  comments = outage.Element("comments").Value
                              };
                                            

            foreach (var outage in alloutages)
            {
                Console.WriteLine($"OUTPUT: {outage.outageID}");
            }

Output:

Hello World!
IENUMBERABLE: 2021-10-16-0002
IENUMBERABLE: 2021-10-16-0001
IENUMBERABLE: Test outage 2primaryCrewPrimary Crew NamestringOutage Name0032.427326-99.788595TRANSFORMER1District9TRANSFORMER1TransformerA10FeederNameAssumed2015-01-01T10:00:00Z2015-01-01T10:30:00Z2015-01-01T11:00:00ZCrew1Crew21010Contractor44

IENUMBERABLE: Test outage 1primaryCrewPrimary Crew NamestringOutage Name0032.427326-99.788595TRANSFORMER1District9TRANSFORMER1TransformerA10FeederNameAssumed2015-01-01T10:00:00Z2015-01-01T10:30:00Z2015-01-01T11:00:00ZCrew11010Contractor44

Error at var = alloutages section, highlighting the 'select new' block.

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=ParseXMLWithLinq
  StackTrace:
   at XMLParse.Program.<>c.<Main>b__0_2(XElement outage) in

System.Xml.Linq.XContainer.Element(...) returned null.

Contents of alloutages looks like this:

<outageEvent objectID="2021-10-16-0002" xmlns="http://www.multispeak.org/Version_4.1_Release">
  <comments>Test outage 2</comments>
  <extensionsList>
    <extensionsItem>
      <extName>primaryCrew</extName>
      <extValue>Primary Crew Name</extValue>
      <extType>string</extType>
       ...
</outageEvent>

CodePudding user response:

The reason for exception is comments element inside outageEvent is in the same namespace as outageEvent, so in http://www.multispeak.org/Version_4.1_Release. So instead of:

select new /*Error Here*/
{
    outageID = outage.Attribute("objectID").Value,
    comments = outage.Element("comments").Value
};

You need to do:

select new /*Error Here*/
{
    outageID = outage.Attribute("objectID").Value,
    // use namespace you already have here
    comments = outage.Element(oecn   "comments").Value
};

Alternative approach is to filter elements by local name:

select new /*Error Here*/
{
    outageID = outage.Attribute("objectID").Value,
    comments = outage.Elements().First(c => c.Name.LocalName == "comments").Value
};
  • Related