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

C#读取XML文件
我想读取如下的XML文件到内存,文件的树状结构是不定的,邮箱和关键字的对应关系可能是一对一,一对多,多对一,多对多。
打算用ArryList11来保存group1节点下的Email字段
  用ArryList12来保存group1节点下的KeyWord字段
依此类推。
看了MSDN的帮助示例,还是不太会操作XML文件,大虾们能否给个思路?
谢谢了。

C# code
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
  
  <group>
    <Email>xxx@163.com</Email>
    <KeyWord>java</KeyWord>
  </group>

  <group>
    <Email>xxx@163.com</Email>
    <KeyWord>sql</KeyWord>
    <KeyWord>数据库</KeyWord>
    <KeyWord>存储过程</KeyWord>
    <KeyWord>游标</KeyWord>
  </group>

  <group>
    <Email>xxx@163.com</Email>
    <Email>xxx@163.com</Email>
    <Email>xxx@163.com</Email>
    <Email>xxx@163.com</Email>
    <KeyWord>求助</KeyWord>
  </group>

  <group>
    <Email>xxx@163.com</Email>
    <Email>xxx@163.com</Email>
    <Email>xxx@163.com</Email>
    <Email>xxx@163.com</Email>
    <KeyWord>c#</KeyWord>
    <KeyWord>C++</KeyWord>
    <KeyWord>c</KeyWord>
  </group>
</Configuration>





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

 private void ReadXml()
    {
        ArrayList ArryList11 = new ArrayList();
        ArrayList ArryList12 = new ArrayList();

        //假设你的xml文件名为demo.xml确保路径正确
        string xmlPath = Server.MapPath("demo.xml");
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(xmlPath);

        XmlNodeList xnl = xmlDoc.SelectSingleNode("Configuration").ChildNodes;


        foreach (XmlNode node in xnl)
        {
            foreach (XmlNode emailnode in node.SelectNodes("Email"))
            {
                ArryList11.Add(emailnode.InnerText);
            }
            foreach (XmlNode keywordnode in node.SelectNodes("KeyWord"))
            {
                ArryList12.Add(keywordnode.InnerText);
            }
        }
    }

------解决方案--------------------
(二). XML学习(Working with XML)

1.幻灯片课程

下载: http://www.cnblogs.com/Files/ChengKing/Working%20with%20XML(ppt).rar

2.示例代码

下载: http://www.cnblogs.com/Files/ChengKing/Working%20with%20XML(project).rar



详细请见:
http://blog.csdn.net/ChengKing/archive/2006/03/31/646363.aspx
------解决方案--------------------
还是使用xml 凡序列化为实体 class 的方式比较易于维护和使用。
构造2个类代码很简单
C# code

public class Configuration
    {
    
        Collection<Group> groups = new Collection<Group>();
        [XmlElement(ElementName = "group")]
        public Collection<Group> Groups
        {
            get { return groups; }
            set { groups = value; }
        }
    }
    
    public class Group
    {
        Collection<string> email = new Collection<string>();
        [XmlElement(ElementName = "Email")]
        public Collection<string> Email
        {
            get { return email; }
            set { email = value; }
        }
        
        Collection<string> keyWord = new Collection<string>();
        [XmlElement(ElementName = "KeyWord")]
        public Collection<string> KeyWord
        {
            get { return keyWord; }
            set { keyWord = value; }
        }
        
    }