Reading node in XML file with namespace?

G

Guest

I'm trying to navigate inside an XML file that has a very simple namespace,
But when I'm using the name space a get nothing (Count == 0) when I do
SelectNodes() or SelectSingleNode() (null).
When I remove the namespace from the XML file and from the code --> the
Select is successful but I do need to leave the namespace in the XML file.

Here is the XML file I'm using:
<?xml version="1.0" standalone="yes"?>
<MyDB xmlns="DataBase.xsd">
<Subjects>
<Subject>
<ID>Cylinder</ID>
<Defects>
<Defect>
<ID>100</ID>
<Sevirity>10</Sevirity>
</Defect>
<Defect>
<ID>101</ID>
<Sevirity>20</Sevirity>
</Defect>
<Defect>
<ID>102</ID>
<Sevirity>30</Sevirity>
</Defect>
</Defects>
</Subject>
</Subjects>
</MyDB>

And the code using DOM:
XmlDocument doc = new XmlDocument();
doc.Load("EvsDB Output.xml");
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ns", "DataBase.xsd");
// or // nsmgr.AddNamespace("", "DataBase.xsd");

XmlNode node = doc.SelectSingleNode("EvsDB/Subjects", nsmgr); // return null
XmlNodeList listSubjects = doc.SelectNodes("/EvsDB/Subjects", nsmgr); //
return listSubjects.Count == 0
XmlNodeList listSubject = doc.SelectNodes("/EvsDB/Subjects/Subject", nsmgr);
// return listSubject.Count == 0
XmlNodeList listDefect =
doc.SelectNodes("/EvsDB/Subjects/Subject/Defects/Defect", nsmgr); // return
listDefect.Count == 0


Can anybody tell hove to make it work?
 
A

Andy

If you go with the ("ns", "DataBase.xsd") manager, you'll need to
prefix ns: before all of your nodes. For example:

XmlNode node = doc.SelectSingleNode("ns:EvsDB/ns:Subjects", nsmgr);

BTW, i haven't had any luck trying to specify the default namespace...i
still end up with null nodes. So just assign a prefix and remember to
use that prefix throughout.

HTH
andy
 
G

Guest

It works, thanks a lot.

BTW: To set a default namespcae, simply do something like:
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("", "DataBase.xsd");
 

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