简体   繁体   中英

How to generate an XML file with specific structure using C#?

I have an XML with the below structure:

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

I've managed to generate a simplified version of the XML with the below structure:

<Entity>
    Attributes here
</Entity>

However the two things I'm struggling with are:

  1. How to add the record ID to "Entity"
  2. How to add the hierarchies in (not sure the terminology for this in XMLs)

The code I have is:

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());
  }

Check the XElement class: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/creating-xml-trees-linq-to-xml-2

The basic example is this:

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

Using the ToString() function on the XElement object will return the value in string format.

To generate attributes like the id, you can use the XAttribute class like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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