How do I set the namespace URI in c#?
Im using a namespace in my xml (I need to use this for xsd validation purposes). Because of this my xpath is no longer working.
I have the code:
XmlDocument doc = new XmlDocument();
doc.Load(newXmlFilePath);
And the XML:
<?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
<title>
A vid with Pete
</title>
<description>
Petes vid
</description>
<contributor>
Pete
开发者_如何学C </contributor>
<subject>
Cat 2
</subject>
</video>
But my xpath doesnt select the node. I tried to set the namespace using:
doc.NamespaceUR = "x";
However its a get only accessor. Any ideas?
XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("vid", "UploadXSD");
Note that you need to use this with your query. For example:
doc.SelectSingleNode("/vid:video/vid:subject", nsMgr);
As otherwise the SelectSingleNode
won't know to operate in the context of that manager.
Check out this Microsoft How To: http://support.microsoft.com/kb/318545
Based on your other recent questions, I think you're trying to deal with a mixture of documents where some are in a particular namespace and some are not - so you're looking to be namespace-agnostic, right?
There are a couple of things you could do. You could use a hack to strip out the namespace - but that has always struck me as a bit fragile. There are other ways to express what is semantically the same document - e.g. the whole thing could use a namespace prefix on every single element - and that trick won't work.
Or you could write namespace-agnostic XPath queries. E.g. "/*[local-name()='video']/*[local-name()='subject']"
精彩评论