tags:

views:

1012

answers:

2

In an ASP.NET 2.0 website, I have a string representing some well-formed XML. I am currently creating an XmlDocument object with it and running an XSL transformation for display in a Web form. Everything was operating fine until the XML input started to contain namespaces.

How can I read in this string and allow namespaces?

I've included the current code below. The string source comes from an HTML encoded node in a WordPress RSS feed.

XPathNavigator myNav= myPost.CreateNavigator();
XmlNamespaceManager myManager = new XmlNamespaceManager(myNav.NameTable);
myManager.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
string myPost = HttpUtility.HtmlDecode("<post>" +
    myNav.SelectSingleNode("//item[1]/content:encoded", myManager).InnerXml +
    "</post>");
XmlDocument myDocument = new XmlDocument();
myDocument.LoadXml(myPost.ToString());

The error is on the last line:

"System.Xml.XmlException: 'w' is an undeclared namespace. Line 12, position 201. at System.Xml.XmlTextReaderImpl.Throw(Exception e) ..."

A: 

Your code looks right.

The problem is probably in the xml document you're trying to load. It must have elements with a "w" prefix, without having that prefix declared in the XML document

For example, you should have:

<test xmlns:w="http://..."&gt;
  <w:elementInWNamespace />
</test>

(your document is probably missing the xmlns:w="http://")

ckarras
A: 

Gut feel - one of the namespaces declared in //content:encoding is being dropped (probably because you're using the literal .InnerXml property)

What's 'w' namespace evaluate to in the myNav DOM? You'll want to add xmlns:w= to your post node. There will probably be others too.

stephbu
You're gut feel is on target. It looks like the post was copy and pasted from MS Word, so the HTML contains attributes with the "w" namespace, but there's no embedded declaration for it.
Mattio