XML构建器遍历每个节点

时间:2014-04-16 08:37:10

标签: c# xml stringbuilder

大家好我所有XML数据都是StringBuilder形成的,如下所示

StringBuilder sb = new StringBuilder();
sb.Append("<?xml version=\"1.0\" encoding=\"utf-16\"?>");
sb.Append("<TEST>"
+ "<DEMO><CONTENTINFO  name=\"Nani\" receiver=\"Lucky\""
+ "/></DEMO></TEST>");
XmlDocument XMLDocument = new XmlDocument();
XMLDocument.LoadXml(sb.ToString());
XmlNodeList nodeList = XMLDocument.FirstChild.ChildNodes;
foreach (XmlNode node in nodeList)
{
}

我尝试使用XMLDocument遍历子节点以获取分割数据所需的数据,以便它应该提供name=Nanireceiver=lucky或将密钥和值存储在dictionary就像dic.Add("name","nani") and dic.Add("receiver","lucky")一样。那么有人可以帮我解决问题

2 个答案:

答案 0 :(得分:0)

如果您希望形成一组强大的类实例,那么请使用XmlSerializer并创建类来表示XML结构的每个级别。

[XmlRoot("TEST")]
public class Test
{
     [XmlElement(Name = "DEMO")]
     public Demo Demo
     {
          get;
          set;
     }
} 

public class Demo
{
    [XmlElement("CONTENTINFO")]
    public ContentInfo ContentInfo
    {
       get;
       set;
    }
}

public class ContentInfo
{
   [XmlAttribute(Name = "name")]
   public string Name
   {
      get;
      set;
   }

   [XmlAttribute(Name = "receiver")]
   public string Reciever
   {
      get;
      set;
   }
}

XmlSerializer serializer = new XmlSerializer(typeof(Test));
serializer.Serialize(....);
Test testInstance = serializer.Deserialize(....);

... etc.

以上代码尚未经过测试,但应该为您提供要点。

答案 1 :(得分:0)

为什么使用StringBuilder生成XML?有更好的方法:

var root = new XDocument();
var test = new XElement("TEST");
var demo = new XElement("DEMO");
var contentInfo = new XElement("CONTENTINFO", 
                  new XAttribute("name", "Nani"), 
                  new XAttribute("receiver", "Lucky"));

demo.Add(contentInfo);
test.Add(demo);
root.Add(test);

要将所需的值提取到字典中,您可以使用以下LINQ查询:

var foo = root.Descendants("DEMO").Elements("CONTENTINFO")
              .SelectMany(x => x.Attributes())
              .ToDictionary(x => x.Name.ToString(), x => x.Value.ToString());

这将为您提供如下字典:

  

键:name =   价值:纳尼,

     

Key:receiver = Value:Lucky