简体   繁体   中英

how to add namespace to the xpath c# correctly?

i tried many different ways but it is keep saying: Data at the root level is invalid. Line 1, position 1. My question is: how can i add the namespace correctly?

if i delete the namespace from the xml, it works perfect but i cant do that because xml document is already created by somebody else.

This is my xml file:

<?xml version="1.0" encoding="utf-8"?>
<outputTree xmlns="http://www.ibm.com/software/analytics/spss/xml/oms" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.ibm.com/software/analytics/spss/xml/oms http://www.ibm.com/software/analytics/spss/xml/oms/spss-output-1.8.xsd">
  <book>
    <book id="bk101">
      <author id="1">Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description> An in-depth look at creating applications with XML.</description>
    </book>
    <book id="bk102">
      <author id="2">Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>
        A former architect battles corporate zombies,an evil sorceress, and her own childhood to become
        queen of the world.
      </description>
    </book>
  </book>
</outputTree>

c

private void GetXMLData()
{
    try
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(@"C:\Users\byilmaz\Desktop\SPSS_SITE\g.xml");

        XmlNamespaceManager nsmanager = new XmlNamespaceManager(doc.NameTable);
        nsmanager.AddNamespace("test", "http://www.ibm.com/software/analytics/spss/xml/oms");

        XmlNodeList errorNodes = doc.SelectNodes("/test:outputTree/", nsmanager);
        foreach (XmlNode errorNode in errorNodes)
        {
            //string errorCode = errorNode.Attributes["id"].Value;
            //string errorMessage = errorNode.InnerText;
        }

    }
    catch (Exception err)
    {
        throw (err);
    }
}

您应该使用Load()方法而不是LoadXml()从文件加载XML:

doc.Load(@"C:\Users\byilmaz\Desktop\SPSS_SITE\g.xml");

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