c# - 如何使用 C# 生成具有特定结构的 XML 文件?
问题描述
我有一个具有以下结构的 XML:
<Entity Record={ID}>
<GeneralInfo>
Attributes here
</GeneralInfo>
<DetailInfo>
Attributes here
</DetailInfo>
</Entity>
我设法生成了具有以下结构的 XML 的简化版本:
<Entity>
Attributes here
</Entity>
然而,我正在努力解决的两件事是:
- 如何将记录 ID 添加到“实体”
- 如何添加层次结构(不确定 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());
}
解决方案
检查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);
推荐阅读
- php - blueimp jquery 文件上传 - 使用标题等数据输入重命名文件名
- javascript - 如何登录 Puppeteer?
- python - 如何在javascript中处理从服务器收到的下载响应
- ios - Apple Watch 在特定屏幕上强制在 iphone 的前台打开应用程序?
- c# - 如何在 Soap Web 服务中使用查询字符串传递参数?
- python - 在 python 中创建一个非常简单的“进化”算法
- dart - 我们如何在 Dart 2 中将 int 转换为 BigInt?
- php - Laravel 在更改新密码时检查旧密码
- javascript - 将dom添加到顶部时如何保持滚动位置
- mysql - 如何在 Flask 中缓存 mysql 连接