简体   繁体   English

无法使用C#和XmlDocument读取XML

[英]Unable to Read XML using C# and XmlDocument

I would like to read a XML File with C#, but i always get an error. 我想用C#读取XML文件,但是总是出现错误。

This is my XML 这是我的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. 我想阅读此XML,但XMLContentNodes始终为null。 So i am unable to get the SelectSingleNode with this Path, but i cant find out what should be wrong here? 因此,我无法使用此路径获取SelectSingleNode,但是我无法找到这里应该出什么问题?

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. 在将XML文件加载到doc XmlDocument对象之后,您需要将名称空间urn:omds20添加到doc XmlDocument对象中。 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: 然后,您可以像这样查询PAKET节点:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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