有些时候我们需要生成一个xml文档作为数据交换的容器。当然我们用拼接字符串的方法来进行构建xml,但是这种方法虽然简单有效,但是如果xml文档结构过于复杂,拼接字符串会让人眼花缭乱。这时候就需要C#给我们提供现成的类库,以供我们自由的创建xml文档。
比如我们要创建如下的xml文档
<?xml version="1.0" encoding="UTF-8"?> <ns0:Z_AVS_UPLOAD_WEIGHT_Request xmlns:ns0="http://schemas.microsoft.com/BizTalk/2003"> <ZWERKS>ZFM1</ZWERKS> <TAB1> <ZNO>13022101</ZNO> <ZORDER>2013238955</ZORDER> <ZWEIGHT>4140</ZWEIGHT> </TAB1> <TAB1> <ZNO>13022101</ZNO> <ZORDER>2013239627</ZORDER> <ZWEIGHT>4140</ZWEIGHT> </TAB1> </ns0:Z_AVS_UPLOAD_WEIGHT_Request>
选取这样的结构,一方面是因为它来自于论坛某位坛友实际的需求,另一方面它足够简单却有代表性。
下面我将以这个例子用两种方法(XmlDocument和Linq to XML)进行讲解。
1、XmlDocument
XmlDocument document = new XmlDocument(); XmlDeclaration declaration = document.CreateXmlDeclaration("1.0", "UTF-8", "");//xml文档的声明部分 document.AppendChild(declaration); XmlElement root = document.CreateElement("ns0", "Z_AVS_UPLOAD_WEIGHT_Request", "http://schemas.microsoft.com/BizTalk/2003"); document.AppendChild(root); XmlElement zwerks = document.CreateElement("ZWERKS"); zwerks.InnerText = "ZFM1"; root.AppendChild(zwerks); XmlElement tab1 = document.CreateElement("TAB1"); root.AppendChild(tab1); XmlElement zno = document.CreateElement("ZNO"); zno.InnerText = "13022101"; tab1.AppendChild(zno); XmlElement zorder = document.CreateElement("ZORDER"); zorder.InnerText = "2013238955"; tab1.AppendChild(zorder); XmlElement zweight = document.CreateElement("ZWEIGHT"); zweight.InnerText = "4140"; tab1.AppendChild(zweight); XmlElement tab2 = document.CreateElement("TAB1"); root.AppendChild(tab2); XmlElement zno2 = document.CreateElement("ZNO"); zno2.InnerText = "13022101"; tab2.AppendChild(zno2); XmlElement zorder2 = document.CreateElement("ZORDER"); zorder2.InnerText = "2013238955"; tab2.AppendChild(zorder2); XmlElement zweight2 = document.CreateElement("ZWEIGHT"); zweight2.InnerText = "4140"; tab2.AppendChild(zweight2); document.Save("test.xml");//将生成好的xml保存到test.xml文件中
2、Linq to XML
XDocument document = new XDocument(); document.Declaration = new XDeclaration("1.0", "UTF-8", ""); XNamespace ns = "http://schemas.microsoft.com/BizTalk/2003"; XElement root = new XElement(ns + "Z_AVS_UPLOAD_WEIGHT_Request", new XAttribute(XNamespace.Xmlns + "ns0", "http://schemas.microsoft.com/BizTalk/2003")); root.Add(new XElement("ZWERKS", "ZFM1"), new XElement("TAB1", new XElement("ZNO", 13022101), new XElement("ZORDER", 2013238955), new XElement("ZWEIGHT", 4140)), new XElement("TAB1", new XElement("ZNO", 13022101), new XElement("ZORDER", 2013238955), new XElement("ZWEIGHT", 4140)) ); document.Add(root); document.Save("test.xml");//保存xml到文件
可以发现Linq to XML的方法比较简洁,代码量也足够小。当然了XmlDocument的方法可以进一步的简化,这里重点展示一下Linq to XML的魅力。
呵呵,如上只当给需要的朋友提供一下思路和解决方案。关于Linq to xml的更多信息可以参考:XNamespace。
转载于:https://blog.51cto.com/csharper/1345986