日期:2014-05-18  浏览次数:20896 次

高分求解 .net中怎么去取xml文件中的节点及属性
xml文件:
a.xml
<?xml version="1.0" encoding="utf-8" ?>
<a a1="1" a2="2">
  <b b1="1">b</b>
  abc
  <c c1="1">c</c>
  abcd
  <d d1="1">
  <e e1="1">e</e>
  </d>
  abcde
</a>

我要去a节点的属性和a的儿子节点!不要儿子节点下的属性和儿子子节点一下的节点!也就是说 b c d 节点的属性不要 和e节点都不用!怎么做啊!谁能告诉我!


------解决方案--------------------
C# code
 XmlDocument x = new XmlDocument();
            x.Load("..\\..\\a.xml");
            XmlNode n = x.SelectSingleNode("/root/a");
            XmlNodeList nl = n.ChildNodes;
            foreach (XmlNode no in nl)
            {
                if (no.NodeType == XmlNodeType.Element) 
                richTextBox1.AppendText(no.Name + "\r\n");
            }
            for (int i = 0; i < n.Attributes.Count; i++)
            {
                richTextBox1.AppendText(n.Attributes[i].Name + "\r\n");
            }

------解决方案--------------------
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\Project\C#Test\WindowsApplication1\WindowsApplication2\XMLFile3.xml");
XmlNode node = doc.SelectSingleNode("/root/a");
foreach (XmlNode el in node.ChildNodes)
{
if (el.Name != "e")
{
Debug.WriteLine("nodeType:"+el.NodeType);
Debug.WriteLine("Text:" + el.InnerText);
if (el.Attributes != null)
{
foreach (XmlAttribute att in el.Attributes)
{
Debug.WriteLine("XmlAttribute:" + att.InnerText);
}
}

}
}
------解决方案--------------------
C# code


 XmlDocument x = new XmlDocument();
            x.Load(Application.StartupPath+"\\a.xml");
            XmlNodeList n = x.SelectNodes("/root/a");
            foreach (XmlNode xm in n)
            {
                for (int i = 0; i < xm.Attributes.Count; i++)
                {
                    richTextBox1.AppendText(xm.Attributes[i].Name + "--" + xm.Attributes[i].Value + "\r\n");
                }
                XmlNodeList nl = xm.ChildNodes;
                foreach (XmlNode no in nl)
                {
                    if (no.NodeType == XmlNodeType.Element)
                        richTextBox1.AppendText(no.Name + "--" + no.InnerText + "\r\n");
                }
            }

------解决方案--------------------
LZ把想要的结果写出个例子来.这样大家好有目标.
在问题上加个补充.
------解决方案--------------------
C# code

XmlDocument x = new XmlDocument();
x.Load(Application.StartupPath+"\\a.xml");
XmlNodeList n = x.SelectNodes("/root/a");
foreach (XmlNode xm in n)
{
    richTextBox1.AppendText("a:element");
    for (int i = 0; i < xm.Attributes.Count; i++)
    {   
      richTextBox1.AppendText("  attribute:"+xm.Attributes[i].Name + "  value="+xm.Attributes[i].Value );
    }
    richTextBox1.AppendText("\r\n");
    XmlNodeList nl = xm.ChildNodes;
    foreach (XmlNode no in nl)
    {
      if (no.NodeType == XmlNodeType.Element)
      richTextBox1.AppendText(" element:"+no.Name + " value=" + no.InnerText);
    }
    richTextBox1.AppendText("\r\n");
}