0

I am currently trying to learn how to parse data, and its a bit confusing. can someone check out my code and see what I'm doing wrong or if im even heading in the right direction.

XML File:

<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# Code:

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;

I am new to C#, I cant find a good example explaining how to successfully use loops to find more then one:

<b:chat />
4

2 回答 2

0

假设以下输入 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 to 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();
    
于 2013-03-08T18:22:43.427 回答
0

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

于 2013-03-08T18:12:46.037 回答