Exitos
Exitos

Reputation: 29720

Why doesnt this xPath (c#) work?

Got this xml:

<?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>

And this xpath:

videoToAdd.Title = doc.SelectSingleNode(@"/video/title").InnerXml;

And im getting an 'object reference not set to an instance of an object'. Any ideas why this is a valid xpath from what I can see and it used to work...

Upvotes: 0

Views: 559

Answers (5)

Pavel Urbanč&#237;k
Pavel Urbanč&#237;k

Reputation: 1496

Your XML contains namespace specification, you need to modify your source to take that into consideration.
Example:

XmlDocument doc = new XmlDocument();
doc.Load("doc.xml");
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(doc.NameTable);
xmlnsManager.AddNamespace("ns", "UploadXSD");

videoToAdd.Title = doc.SelectSingleNode(@"/ns:video/ns:title", xmlnsManager).InnerXml;

Upvotes: 6

batwad
batwad

Reputation: 3665

It's the xmlns="UploadXSD" attribute causing you grief here. I think you'll need to use a XmlNamespaceManager to help the parser resolve the names, or remove the xmlns attribute if you don't need it.

Upvotes: 1

Ryan Bigg
Ryan Bigg

Reputation: 107728

Try this:

videoToAdd.Title = doc.SelectSingleNode(@"//xmlns:video/xmlns:title").InnerXml;

Your XML document has an XML namespace and to find the elements you must prefix them with xmlns:.

Upvotes: 0

Michael
Michael

Reputation: 9058

Is it possible that the doc variable points to the <video> element? In that case you would need to write either

videoToAdd.Title = doc.SelectSingleNode(@"./title").InnerXml;

or

videoToAdd.Title = doc.SelectSingleNode(@"//video/title").InnerXml;

Upvotes: 0

Paul Butcher
Paul Butcher

Reputation: 6956

/video/title would return a title element with no namespace, from within a video element with no namespace.

You need to either remove xmlns="UploadXSD" from your xml, or set an appropriate selection namespace in your C#

Upvotes: 1

Related Questions