正在读取XML和未声明的命名空间

本文关键字:未声明 命名空间 XML 读取 | 更新日期: 2024-07-23 02:47:42

我在尝试读取XML文件时收到了此错误消息

 Unhandled Exception: System.Xml.XmlException: 'xi' is an undeclared namespace. Line 12, position 18.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(String res, String arg, Int32 lineNo, Int32 linePos)
   at System.Xml.XmlTextReaderImpl.LookupNamespace(NodeData node)
   at System.Xml.XmlTextReaderImpl.ElementNamespaceLookup()
   at System.Xml.XmlTextReaderImpl.ParseAttributes()
   at System.Xml.XmlTextReaderImpl.ParseElement()
   at System.Xml.XmlTextReaderImpl.ParseElementContent()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.XmlTextReader.Read()

读取XML:的代码

   XmlTextReader reader = new XmlTextReader("file.xml");
    while (reader.Read())
    {
        // Do some work here on the data.
        Console.WriteLine(reader.Name);
    }
    Console.ReadLine();

xml文件:

<?xml version="1.0" encoding="ISO-8859-1"?>    
<doh> 
        <!-- Available Resources-->
        <servers>
                <xi:include href="file.xml"/>
        </servers>

正在读取XML和未声明的命名空间

我假设您想要使用XInclude。您必须定义xi前缀映射到哪个命名空间。最简单的原因是在根元素中包含命名空间映射。

  <doh xmlns:xi="http://www.w3.org/2001/XInclude">

请注意,XmlTextReader将不包含"file.xml"。您必须通过其他代码"include"。关于XInclude的一篇很好的背景论文可以在MSDN上找到,网址是http://msdn.microsoft.com/en-us/library/aa302291.aspx