Problem parsing XML with a namespace

M

Michael Bray

I have some XML that is being generated by an external component and
structurally looks like this:

<?xml version='1.0' ?>
<rootObject xmlns='http://company.com/root.xsd'>
<subElement>Value</subElement>
</rootObject>

The 'http://company.com/root.xsd' doesn't actually exist, but I didn't
think that mattered.. I have some utility functions that I use to help me
process the XML document, such as:

public static XmlNameSpaceManager nsm = null;
public static bool NodeExists(XmlNode sNode, string sNodeXPath)
{
return (sNode.SelectSingleNode(sNodeXPath, nsm) != null);
}

and I would normally use it like:

string srcXML = "...the XML shown above...";
XMLDocument xmlDoc = new XMLDocument();
xmlDoc.LoadXML(srcXML);
bool b = NodeExists(xmlDocument.DocumentElement, "/rootObject");

If the source XML has the 'xmlns' tag, then NodeExists returns'false',
whereas if I take out the xmlns attribute tag, it returns 'true'. I want
it to always return true (ignoring namespaces).

So a few questions:

1. Why is the added namespace causing the NodeExists to return false?
2. How can I get the SelectSingleNode to perform as I need it to, ignoring
(or at least accounting for) the added namespace attribute?

Normally, I use this code with nsm set to null. (In fact, until just now,
I was using the SelectSingleNode that didn't specify nsm at all.) I've
tried setting the 'nsm' variable just prior to calling NodeExists:

nsm = new XMLNameSpaceManager(xmlDoc.NameTable);

and I've also tried adding the namespace:

nsm.AddNamespace(string.Empty, "http://company.com/root.xsd");

but neither of these seem to help...

What can I do??

-mdb
 
M

Marc Gravell

A workaround when using xml with a default namespace declaration:

Add an alias (prefix) to the default namespace (e.g. "x" is this example):
nsm.AddNamespace("x", "http://company.com/root.xsd");
(note: might want to read this dynamically from the xmlns attribute on the
doc-element to save hard-coding)

and then use that as a prefix on every xpath expression:
bool b = NodeExists(xmlDocument.DocumentElement, "/x:rootObject");

Note that a longer xpath might be "x:Something/x:SomethingElse/x:TheOther" -
you get the idea.

Hope this helps,

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top