[英]How to generate an XML file with specific structure using C#?
I have an XML with the below structure:我有一个具有以下结构的 XML:
<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:我设法生成了 XML 的简化版本,其结构如下:
<Entity>
Attributes here
</Entity>
However the two things I'm struggling with are:然而,我正在努力解决的两件事是:
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检查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.在XElement
object 上使用 ToString() function 将以字符串格式返回值。
To generate attributes like the id, you can use the XAttribute
class like this:要生成像 id 这样的属性,您可以像这样使用XAttribute
class:
XElement phone = new XElement("Phone",
new XAttribute("Type", "Home"),
"555-555-5555");
Console.WriteLine(phone);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.