JPAnderson
JPAnderson

Reputation: 59

LINQ to XML how do I get child element value with multiple namespace

I have an xml document here:

<?xml version="1.0" encoding="utf=8"?>
<package xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <metadata xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
    <id>NugetName</id>
    <version>1.0.0</version>
    <authors>company</authors>
    <owners>company</owners>
  </metadata>
  <files>
  ...
  </files>
</package>

I'm trying to get the value of "id". I'm currently using XDocument and i've tried several different ways to go about this.

I thought for certain I could use the following:

XDocument xmlDoc = XDocument.Load(file);
XNamespace xns = "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd";
XElement el = xmlDoc.Element(xns + "metadata");
XElement id = el.Element(xns + "id");
string idValue = id.Value;
Console.WriteLine(idValue);

However, I get Error: Object reference not set to an instance of an object. I'm not sure how Element can be null. Do I need to declare project namespace too? I've tried that and I still get the Object reference error. Could someone point out the novice mistake I've made?

Upvotes: 1

Views: 553

Answers (1)

Pankaj Kapare
Pankaj Kapare

Reputation: 7802

Since your root element also has namespace you select root element using namespace and using that reference you can reference metadata element. Simplest fix would be replace following line

XElement el = xmlDoc.Element(xns + "metadata");

with

XElement el = xmlDoc.Root.Element(xns + "metadata");

Upvotes: 1

Related Questions