创建XML 标签

            //创建XMl
            XmlDocument doc = new XmlDocument();
            //  创建根结点
            XmlElement XMLroot = doc.CreateElement("Request");
            doc.AppendChild(XMLroot);
            XMLroot.SetAttribute("service", "OrderService");
            XMLroot.SetAttribute("lang", "zh-CN");
            //创建Head节点
            XmlElement HeadRoot = doc.CreateElement("Head");
            XMLroot.AppendChild(HeadRoot);
            HeadRoot.InnerText = head;
            //创建Body节点
            XmlElement BodyRoot = doc.CreateElement("Body");
            XMLroot.AppendChild(BodyRoot);

            XmlElement OrderRoot = doc.CreateElement("Order");
            BodyRoot.AppendChild(OrderRoot);
OrderRoot.SetAttribute("j_company", j_company);//电子面单 必填 OrderRoot.SetAttribute("j_contact", j_contact);//电子面单 必填 OrderRoot.SetAttribute("j_tel", j_tel);//电子面单 必填 OrderRoot.SetAttribute("j_mobile", ""); OrderRoot.SetAttribute("j_province", ""); //创建标签<Cargo></Cargo>,将Cargo放在Order标签里 XmlElement Cargoroot = doc.CreateElement("Cargo"); OrderRoot.AppendChild(Cargoroot); Cargoroot.SetAttribute("name", "电子产品"); Cargoroot.SetAttribute("count", model.TripPieceQty); return doc.InnerXml.ToString();

展示:

<Request service="OrderService" lang="zh-CN">
    <Head>0215615871</Head>
    <Body>
        <Order orderid="xxxx" 
                j_company="xxxx" 
                j_contact="xxxx"                           
                j_address="xxxx"                
                >
            <Cargo name="电子产品" count="2" />
        </Order>
    </Body>
</Request>
public static XDocument GenerateRouteRequest(string customer, string tracking, string CUSTOMER_TEL)
    {
        var xd = new XDeclaration("1.0", "UTF-8", "yes");
        var xRequest = new XElement("Request", new XAttribute("service", "RouteService"), new XAttribute("lang", "zh-CN"));
        xRequest.Add(
                    new XElement("Head", customer),//0215615871
                    new XElement("Body",
                            new XElement("RouteRequest",
                                        new XAttribute("aa", "1"),
                                        new XAttribute("bb", "1"),
                                        new XAttribute("cc", CUSTOMER_TEL),
                                        new XAttribute("dd", tracking)
                                        )
                                 )
                    );
        return new XDocument(xd, xRequest);
    }

继续展示: 

<Request service="RouteService" lang="zh-CN">
    <Head>xxxx</Head>
    <Body>
        <RouteRequest tracking_type="1" method_type="1" check_phoneNo="xxx" tracking_number="xxxx" />
    </Body>
</Request>
原文地址:https://www.cnblogs.com/ZkbFighting/p/13820758.html