XmlDocument基本应用

public static void PrintXml(Dictionary<string, string> dic)
        {
            //创建XML文档
            XmlDocument xmlDocument = new XmlDocument();
            XmlText xmlText;
            XmlElement xmlElement;
            
            //在XML文档的最顶部加入声明段落 <?xml version="1.0"?>
            XmlNode xmlNode = xmlDocument.CreateNode(XmlNodeType.XmlDeclaration,"测试","test");
            xmlDocument.AppendChild(xmlNode);


            //不能再次添加 XmlElement节点,同一节点下不能添加2个同级别节点
            //XmlElement outShell = xmlDocument.CreateElement("最外层");
            //xmlDocument.AppendChild(outShell);
            //XmlText outValu = xmlDocument.CreateTextNode("最外层值");
            //outShell.AppendChild(outValu);


            //为XML文档加入一个元素/加入根元素
            XmlElement xmlRoot = xmlDocument.CreateElement("","Response","www.baidu.com");
            xmlDocument.AppendChild(xmlRoot);


            foreach (var item in dic)
            {
                xmlElement = xmlDocument.CreateElement(item.Key);
                xmlText = xmlDocument.CreateTextNode(item.Value);
                xmlElement.AppendChild(xmlText);
                xmlRoot.AppendChild(xmlElement);
            }
            Console.WriteLine(ConvertXmlToString(xmlDocument));

        }

总结:由XmlDocument 实例化对象 通过CreateElement(创建指定元素xmlElement)CreateTextNode(创建指定文本(元素赋值xmlText)),再由元素AppendChild赋值,父级元素AppendChild添加节点

           


猜你喜欢

转载自blog.csdn.net/ID_Dexter/article/details/80226875