【问题标题】:How to generate an XML file with specific structure using C#?如何使用 C# 生成具有特定结构的 XML 文件?
【发布时间】:2020-08-19 10:33:31
【问题描述】:

我有一个具有以下结构的 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# .net xml serialization


    【解决方案1】:

    检查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")  
                )  
            )  
        );
    

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

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

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

    【讨论】:

    猜你喜欢
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    相关资源
    最近更新 更多