1

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?

3
  • Can you place a breakpoint on the xmlDoc variable and trace it through to see whether or not the XML file has been correctly loaded? I cant see where the file parameter has been initialised so its hard to know if the doc itself is null Commented May 16, 2017 at 16:05
  • Trying to figure out what's wrong with my debugger but in the mean time i put the xml document into a string literal and passed it using XDocument.Parse like this; XDocument xmlDoc = XDocument.Parse(str); I get the same error. Commented May 16, 2017 at 16:31
  • Sounds like your document is null Commented May 16, 2017 at 16:43

1 Answer 1

1

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");
Sign up to request clarification or add additional context in comments.

1 Comment

That did the trick. Now I need to figure out if there's a way to dynamically get the namespace because it could change based on the nuspec i feed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.