ASP.NET InnerXml automatically / incorrectly adds attribute text to tags
So, I have XML in the following format:
<somenode>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title/>
</head>
<body>
<p>P one</p>
<p>Another p</p>
</body>
</html>
</somenode>
There is some html inside that I thought would not be a problem as it would just be treated as xml.
I am trying to select the content (InnerXml) of an object <body> tag. However, using
xmlDoc.SelectSingleNode("somenode/html/body")
returns null
and using
xmlDoc.GetElementsByTagName("body")[0].InnerXml
gives InnerXml, but each <p> is added xmlns="http://www.w3.org/1999/xhtml"
, so the output looks like this:
<p xmlns="http://www.w3.org/1999/xhtml">P one</p><p xmlns="http://www.w3.org/1999/xhtml">Another p</p>
Can anyone shed some light on this? Looks like some really strange behavior, any help would be appreciated. I am using ASP.net 2.0 only, so unfortunately trying linq is not an option.
source to share
Your xpath expression does not specify a default namespace. What about:
XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsMgr.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");
XmlNode node = xmlDoc.SelectSingleNode("somenode/xhtml:html/xhtml:body", nsMgr);
source to share
Since the element <html>
defines the default namespace http://www.w3.org/1999/xhtml . All elements within it without a namespace prefix have the same default namespace.
Since the content of the body tag is 2 separate elements <p>
, they both get a declaration. If you have other elements inside your elements <p>
, they will not have a declaration on them.
source to share