开发者

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...


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;


/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#


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.


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;


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:.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜