C#XML - 帮助创建带ID的新标签?

时间:2014-05-28 16:18:49

标签: c# xml

我希望创建一个类似这样的文件:http://pastebin.com/89kuK8h2

有一个标记,在本例中我是从MSDN获得的,客户标记也有一个值,但仍以< \ Customer>:

结尾

客户CustomerID =“HELLO”> //< ----这条线

我想知道如何做到这一点

目前我正在创建以下标签:

XmlNode xHeader = xDoc.CreateElement("Customer");

并附加如下:

xDoc.DocumentElement.AppendChild(xHeader);
            xHeader.AppendChild(xCustomerID);

2 个答案:

答案 0 :(得分:0)

XDocument可能是一种前进的方式,因为它的API更简单:

var root = new XDocument("Root", 
     new XElement("Customers"),
        new XElement("Customer",
           new XAttribute("CustomerID", "HELLO"),
           new XElement("CompanyName", this.CompanyName),
           new XElement("ContactName", this.ContactName),
           new XElement("ContactTitle", this.ContactTitle),
           new XElement("Phone", this.Phone),
           new XElement("FullAddress", 
              new XElement("Address", "..."),
              new XElement("Region", "...")

           )
        )
    );

答案 1 :(得分:0)

我建议你使用LINQ to XML。构建xml很容易:

var xdoc = new XDocument(
    new XElement("Root",
        new XElement("Customers",
            new XElement("Customer",
                new XAttribute("CustomerID", "HELLO"),
                new XElement("CompanyName", "Great Lakes Food Market"),
                new XElement("ContactName", "Howard Snyder"),
                new XElement("ContactTitle", "Marketing Managerr"),
                new XElement("Phone", "(503) 555-7555"),
                new XElement("FullAddress",
                    new XElement("Address", "2732 Baker Blvd."),
                    new XElement("City", "Eugene"),
                    new XElement("Region", "OR")
                    new XElement("PostalCode", "97403")
                    new XElement("Country", "USA")
                    )
                )
        )));

建议阅读:Creating XML Trees in C# (LINQ to XML)