简体   繁体   English

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

[英]C# XML - Help creating new tag with an ID?

I wish to create a file somewhat like this: http://pastebin.com/89kuK8h2 我希望创建一个像这样的文件: http : //pastebin.com/89kuK8h2

There is a tag, and in this example I got from MSDN, the customer tag also has a value and still ends in <\\Customer>: 有一个标签,在这个示例中,我是从MSDN获得的,客户标签也有一个值,并且仍然以<\\ Customer>结尾:

Customer CustomerID="HELLO"> // <---- This Line Customer CustomerID =“ HELLO”> // <----此行

I want to know how to do that 我想知道怎么做

Currently I am creating tags like: 目前,我正在创建类似的标签:

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

and appending like this: 并像这样追加:

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

XDocument may be a way forward here, as its API is much simpler: 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", "...")

           )
        )
    );

I suggest you to use LINQ to XML. 我建议您使用LINQ to XML。 It's easy to build your 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")
                    )
                )
        )));

Suggested reading: Creating XML Trees in C# (LINQ to XML) 建议阅读: 用C#创建XML树(LINQ to XML)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM