使用命名空间读取 xml

Read xml with namespace

我可以像这样阅读 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

这样的命名空间

我收到一个错误 "Object reference not set to an instance of an object" 错误。我需要添加什么才能阅读 xml?

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

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