有这样的一个xml文件结构:
<?xml version="1.0" encoding="utf-8" ?>
<EmpInfoList></EmpInfoList>现在要做的是编程往<EmpInfoList></EmpInfoList>里插入子节点,子节点是雇员信息,子节点的内容是<EmpInfo><EmpID>001</EmpID><EmpName>John</EmpName></Empinfo>,请问用c#该如何实现?

解决方案 »

  1.   


     XmlDocument xmlDoc=new XmlDocument();
     xmlDoc.Load("文件名.xml");
     XmlNode root=xmlDoc.SelectSingleNode("EmpInfoList");//查找<EmpInfoList> XmlElement xe=xmlDoc.CreateElement("EmpInfo");//创建一个<EmpInfo>节点
     XmlElement xesub=xmlDoc.CreateElement("EmpID");
     xesub.InnerText="001";//
     xe.AppendChild(xesub);//添加到<book>节点中
     XmlElement xesub=xmlDoc.CreateElement("EmpName");
     xesub.InnerText="John"; xe.AppendChild(xesub);
     root.AppendChild(xe);//添加到<EmpInfoList>节点中
     xmlDoc.Save("文件名.xml");
      

  2.   


    public static XmlDocument GetXmlDocument(string xml)
            {
                XmlDocument xmldocument = null;
                try
                {
                    xmldocument = new XmlDocument();
                    xmldocument.LoadXml(xml);
                }
                catch (Exception)
                {
                    xmldocument = null;
                }
                return xmldocument;
            }
     XmlDocument xmldocument = GetXmlDocument("你的xml");
    XmlNode EmpInfonode = xmldocument.CreateElement("EmpInfo");
                XmlNode EmpIDnode = xmldocument.CreateElement("EmpID");
                EmpIDnode.InnerText = "001";
                XmlNode EmpNameNode = xmldocument.CreateElement("EmpName");
                EmpNameNode.InnerText = "John ";
                EmpInfonode.AppendChild(EmpIDnode);
                EmpInfonode.AppendChild(EmpNameNode);
                xmldocument.DocumentElement.AppendChild(EmpInfonode);
      

  3.   

    XmlDocument document = new XmlDocument();
                document.Load(@"c:\1.xml");
                XPathNavigator navigator = document.CreateNavigator();            navigator.MoveToChild("EmpInfoList","");            navigator.AppendChild("<EmpInfo> <EmpID>001 </EmpID> <EmpName>John </EmpName> </EmpInfo>");            document.Save(@"c:\1.xml");
      
    *****************************************************************************
    欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码) http://feiyun0112.cnblogs.com/
      

  4.   

    学习
    XML说简单也简单.
    说难它还真不好掌握.
      

  5.   

    执行到xmlDoc.Load("文件名.xml")时候抛出异常,显示“行级别上数据无效。行1,位置1”!是不是<?xml version="1.0" encoding="utf-8" ?> 
    有问题?
      

  6.   

    改好了,程序里面用的方法是xmlDoc.LoadXml就抛出异常,改成xmlDoc.Load("文件名.xml")就好了,一开始没看清!谢谢各位!