语言到xml前缀解析错误

本文关键字:错误 前缀 xml 语言 | 更新日期: 2023-09-27 18:03:06

我目前正在学习如何解析数据,这有点令人困惑。有人可以检查我的代码,看看我做错了什么,或者如果我甚至在正确的方向前进。

XML文件:

<xml xmlns:a='BLAH'
     xmlns:b='BLAH'
     xmlns:c='BLAH'
     xmlns:d='BLAH'>
  <a:info>
   <b:cat Option1='blah' Option2='blah' Option3='blah' />
  </a:info>
</xml>
c#代码:

XmlDocument doc = new XmlDocument();
doc.Load(richTextBox2.Text);
XmlNamespaceManager man = new XmlNamespaceManager(doc.NameTable);
man.AddNamespace("a", "BLAH");
man.AddNamespace("b", "BLAH");
man.AddNamespace("c", "BLAH");
man.AddNamespace("d", "BLAH");
XmlNode temps = doc.SelectSingleNode("/a:info/b:cat/Option1/", man);
richTextBox1.Text = temps.InnerText;

我是c#的新手,我找不到一个很好的例子解释如何成功地使用循环来查找多个循环:

<b:chat />

语言到xml前缀解析错误

如果您正在寻找LINQ to XML,您正在使用错误的API。请使用XDocument类。

假设以下输入的xml文档(请注意名称空间url):

<xml xmlns:a='http://localhost/scheme_a'
     xmlns:b='http://localhost/scheme_b'
     xmlns:c='http://localhost/scheme_c'
     xmlns:d='http://localhost/scheme_d'>
    <a:info>
       <b:cat Option1='1' Option2='1' Option3='1' />
    </a:info>
    <a:info>
       <b:cat Option1='2' Option2='2' Option3='2' />
    </a:info>
</xml>

有获取所有<b:chat />元素的方法。

  1. XmlDocument类:

    var xmlDocument = new XmlDocument();
    xmlDocument.Load(...);
    var xmlNamespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
    xmlNamespaceManager.AddNamespace("a", "http://localhost/scheme_a");
    xmlNamespaceManager.AddNamespace("b", "http://localhost/scheme_b");
    xmlNamespaceManager.AddNamespace("c", "http://localhost/scheme_c");
    xmlNamespaceManager.AddNamespace("d", "http://localhost/scheme_d");
    var bCatNodes = xmlDocument.SelectNodes("/xml/a:info/b:cat", xmlNamespaceManager);
    var option1Attributes = bCatNodes.Cast<XmlNode>().Select(node => node.Attributes["Option1"]);
    // Also, all Option1 attributes can be retrieved directly using XPath:
    // var option1Attributes = xmlDocument.SelectNodes("/xml/a:info/b:cat/@Option1", xmlNamespaceManager).Cast<XmlAttribute>();
    
  2. LINQ到XML XDocument类。XName可以与名称空间一起传递给Descendants()和Element()方法。

    使用Descendants()获取所有<b:chat />元素

    var xDocument = XDocument.Load(...);
    XNamespace xNamespace = "http://localhost/scheme_b";
    var xElements = xDocument.Descendants(xNamespace + "cat");
    // For example, get all the values of Option1 attribute for the b:chat elements:
    var options1 = xElements.Select(element => element.Attribute("Option1")).ToList();