简体   繁体   中英

Unable to Read XML using C# and XmlDocument

I would like to read a XML File with C#, but i always get an error.

This is my XML

<?xml version="1.0" encoding="ISO-8859-1"?>
<OMDS xmlns="urn:omds20" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="urn:omds20 ./omds26-00.xsd">
   <PAKET VUNr="014" PaketZpktErstell="2014-08-29T10:45:08.575" PaketZpktLetztErstell="2014-08-29T10:45:08.575" PaketInhCd="VM" PaketUmfCd="G" VUVersion="26-00" DVRNrAbs="0">
       <PERSON ....
       <PERSON ....
       <PERSON ....

I would like to read this XML, but XMLContentNodes is always null. So i am unable to get the SelectSingleNode with this Path, but i cant find out what should be wrong here?

XmlDocument doc = new XmlDocument();
doc.Load(openFileDialog1.FileName);

XmlNode XMLContentNodes = doc.SelectSingleNode("/OMDS/PAKET"); // Error Here
XmlNodeList PersonNodeList = XMLContentNodes.SelectNodes("PERSON");
foreach (XmlNode node in PersonNodeList)
{
    .....

Any help would be greatly appreciated.

The usual namespace problem. Try

XmlNamespaceManager mgr = new XmlNamespaceManager(new NameTable());
mgr.AddNamespace("d", "urn:omds20");
XmlNode XMLContentNodes = doc.SelectSingleNode("/d:OMDS/d:PAKET", mgr); 
XmlNodeList PersonNodeList = XMLContentNodes.SelectNodes("d:PERSON", mgr);

You'll need to add the namespace urn:omds20 to the doc XmlDocument object after loading your XML file in it. It will look like the following:

XmlDocument doc = new XmlDocument();
doc.Load(openFileDialog1.FileName);

XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(doc.NameTable);
xmlnsManager.AddNamespace("omds20", "urn:omds20");

Then you can query for the PAKET node like this:

XmlNode paketNode = doc.SelectSingleNode("/omds20:OMDS/omds20:PAKET", xmlnsManager);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM