smitchelluk
smitchelluk

Reputation: 172

Returning Data from XML file with Multiple NameSpaces C#

I am having trouble returning data from a Linq to XML query. I have the following XML

<sdnList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/sdnList.xsd">
  <publshInformation>
    <Publish_Date>03/14/2013</Publish_Date>
    <Record_Count>5440</Record_Count>
  </publshInformation>
</sdnList>

I am trying to get the value of Publish Date using the following

XDocument xDoc = XDocument.Load(fileName);
XNamespace xNS = "http://tempuri.org/sdnList.xsd";
XNamespace xNS1 = "http://www.w3.org/2001/XMLSchema-instance";
string strCurrentDate = xDoc.Element(xNS1 + sdnList").Element("publshInformation").Element("Publish_Date").Value; 

This just returns an object expected error. I know my problem is around the namespaces (and most likely is will be a simple solutions)

Thanks

Upvotes: 1

Views: 470

Answers (2)

This will work:

XNamespace xNS = "http://tempuri.org/sdnList.xsd";
string strCurrentDate = xDoc.Element(xNS + "publshInformation").Element(xNS + "Publish_Date").Value;

Upvotes: 1

Ian Roberts
Ian Roberts

Reputation: 122394

All the elements in that document are in the http://tempuri.org/sdnList.xsd namespace, so you need something like

xDoc.Element(xNS + "sdnList")
    .Element(xNS + "publshInformation")
    .Element(xNS + "Publish_Date").Value;

Upvotes: 2

Related Questions