joerdie
joerdie

Reputation: 379

Selecting XML nodes using LINQ

I am trying to select out the "publishInformation" node, (specifically the "Publish_Date" value) from the following xml.

<?xml version="1.0" standalone="yes"?>
    <sdnList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <publshInformation>
        <Publish_Date>04/06/2018</Publish_Date>
        <Record_Count>6297</Record_Count>
    </publshInformation>
    <sdnEntry>
        <uid>36</uid>
        <lastName>TestLastName</lastName>
        <sdnType>Entity</sdnType>
        <addressList>
          <address>
             <uid>25</uid>
             <city>TestCity</city>
             <country>TestCountry</country>
          </address>
        </addressList>
    </sdnEntry>
    </sdnList>

All of my attempts get null results and I am not sure what I am missing. Below is my most recent attempt.

XElement root = XElement.Load(model.InputStream);
XElement publishInformation = root.Descendants("sdnList")
                    .Descendants("publshInformation")
                    .SingleOrDefault();

Using JohnyL's suggestion the code is below.

string xmlstring;
using (StreamReader reader = new StreamReader(model.OfacXml.InputStream))
{
    xmlstring = reader.ReadToEnd();
}

var xml = XElement.Parse(xmlstring);
var dates = xml.Elements("publshInformation").Select(pi => 
    pi.Element("Publish_Date").Value);

I am still getting null in dates with this code.

Upvotes: 2

Views: 44

Answers (1)

JohnyL
JohnyL

Reputation: 7122

var text = 
    @"<?xml version='1.0' standalone='yes'?>
        <sdnList xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
            <publshInformation>
                <Publish_Date>04/06/2018</Publish_Date>
                <Record_Count>6297</Record_Count>
            </publshInformation>
            <sdnEntry>
                <uid>36</uid>
                <lastName>TestLastName</lastName>
                <sdnType>Entity</sdnType>
                <addressList>
                    <address>
                        <uid>25</uid>
                        <city>TestCity</city>
                        <country>TestCountry</country>
                    </address>
                </addressList>
            </sdnEntry>
        </sdnList>";

var xml = XElement.Parse(text);
var dates = xml.Elements("publshInformation").Select(pi => pi.Element("Publish_Date").Value);
dates.ToList().ForEach(WriteLine);

If you'd like to use XDocument instead of XElement:

var xml = XDocument.Parse(text);
var dates = xml.Element("sdnList")
               .Elements("publshInformation")
               .Select(pi => pi.Element("Publish_Date").Value);

Upvotes: 1

Related Questions