2017-02-09 157 views
0

我可以读这样的XML ...未设置为一个实例读取XML命名空间

var xml = new XmlDocument(); 
    xml.Load(fileName); 


    var myVal = SingleElement(xml, "BOOKS/AUTHOR/NAME") 

    public string SingleElement(XmlDocument xdoc, string thePath) 
    { 
     string value; 
     try 
     { 
      return xdoc.SelectSingleNode(thePath).InnerText; 
     } 
     catch (Exception x) 
     { 
      value = string.Empty; 
     } 

     return value; 
    } 

但如果XML文件具有类似<ns0:BOOKS

命名空间我得到一个错误“对象引用的对象“错误。为了能够读取xml,我需要添加什么?

回答

0

您可以使用XmlNamespaceManager添加命名空间。

XmlNamespaceManager namespacemgr = new XmlNamespaceManager(xdoc.NameTable); 
     namespacemgr.AddNamespace("ns", "xxx"); 
     XmlNode node = criteria.SelectSingleNode("/ns:Books", namespacemgr);