[英]How to generate an XML file with specific structure using C#?
我有一个具有以下结构的 XML:
<Entity Record={ID}>
<GeneralInfo>
Attributes here
</GeneralInfo>
<DetailInfo>
Attributes here
</DetailInfo>
</Entity>
我设法生成了 XML 的简化版本,其结构如下:
<Entity>
Attributes here
</Entity>
然而,我正在努力解决的两件事是:
我的代码是:
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());
}
检查XElement
class: 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
object 上使用 ToString() function 将以字符串格式返回值。
要生成像 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.