首页 > 解决方案 > 如何使用 C# 生成具有特定结构的 XML 文件?

问题描述

我有一个具有以下结构的 XML:

<Entity Record={ID}>
    <GeneralInfo>
        Attributes here
    </GeneralInfo>
    <DetailInfo>
        Attributes here
    </DetailInfo>
</Entity>

我设法生成了具有以下结构的 XML 的简化版本:

<Entity>
    Attributes here
</Entity>

然而,我正在努力解决的两件事是:

  1. 如何将记录 ID 添加到“实体”
  2. 如何添加层次结构(不确定 XML 中的术语)

我的代码是:

try
 {
    DataTable dt = new DataTable{ TableName = "Entity" };
    OleDbDataAdapter adapter = new OleDbDataAdapter();
    adapter.Fill(dt, Dts.Variables["User::ResultSet"].Value);
    MessageBox.Show(dt.Rows.Count.ToString());
    
    System.IO.StringWriter writer = new System.IO.StringWriter();
    
    dt.WriteXml(writer, XmlWriteMode.IgnoreSchema, false);
    
    string xmlOutput = writer.ToString();
    
    File.WriteAllText(output, xmlOutput);
    
 } 
catch (Exception e)
  {
    MessageBox.Show(e.Message.ToString());
  }

标签: c#.netxmlserialization

解决方案


检查XElement课程:https ://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/creating-xml-trees-linq-to-xml-2

基本示例是这样的:

XElement contacts =  
    new XElement("Contacts",  
        new XElement("Contact",  
            new XElement("Name", "Patrick Hines"),
            new XElement("Phone", "206-555-0144"),  
            new XElement("Address",  
                new XElement("Street1", "123 Main St"),  
                new XElement("City", "Mercer Island"),  
                new XElement("State", "WA"),  
                new XElement("Postal", "68042")  
            )  
        )  
    );

在对象上使用 ToString() 函数XElement将以字符串格式返回值。

要生成像 id 这样的属性,您可以使用这样的XAttribute类:

XElement phone = new XElement("Phone",  
    new XAttribute("Type", "Home"),  
    "555-555-5555");  
Console.WriteLine(phone);

推荐阅读