I have some code that reads from xml files with a namespace using XmlDocument.My challenge is that i have the namespace of the file i'm reading hard coded for now and i pass that to the XmlNamespaceManager.I would like for my approach to be a little more flexible.To read from any kind of xml file.If it has a namespace,then use the namespace manager to read the elements without hard coding the namespace.If the file doesn't have a namespace,then go ahead and just parse it.Below is what I've done.
xmldoc = new XmlDocument ();
xmldoc.Load (fileLocation);
XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(xmldoc.NameTable);
nameSpaceManager.AddNamespace ("ns","http://schemas.sample.data.org/2005");
XmlNodeList nodeList = xmldoc.SelectNodes("/ns:Demo/ns:Items", nameSpaceManager);
if (nodeList != null)
{
foreach (XmlNode childNode in nodeList)
{
string first = childNode.SelectSingleNode ("ns:First", nameSpaceManager).InnerText;
string second= childNode.SelectSingleNode ("ns:Second", nameSpaceManager).InnerText;
string third = childNode.SelectSingleNode ("ns:Third", nameSpaceManager).InnerText;
}
}
Here's the sample xml file i'm using
<Demo xmlns:i="http://www.justasample.com" xmlns="http://schemas.sample.data.org/2005">
<Items>
<First>first</First>
<Second>second</Second>
<Third>third</Third>
</Items>
</Demo>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…