我正在尝试构建XML文档的一部分,以包含在最终文档中.
使用XDocument时,出现异常:
“This operation would create an incorrectly structured document.”
因为我的片段有多个“根”节点.
由于文件将包含在较大的文档中,因此我的基本元素将不会最终出现在最终文档的根目录中.
XDocument constsdocument = new XDocument(
new XComment($" Consts section generated on {DateTime.Now} "),
new XComment($" First group of constants. "),
FirstTextConsts(MyFirstCollection),
new XComment($" Refrigerant constants. "),
SecondTextConsts(MySecondCollection)
);
// To avoid xml file starting with <?xml version="1.0" encoding="utf-8"?> use stringbuilder and StreamWriter.
StringBuilder sb = new StringBuilder();
XmlWriterSettings xws = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Indent = true
};
using (XmlWriter xw = XmlWriter.Create(sb, xws))
{
constsdocument.Save(xw);
}
System.IO.StreamWriter file = new System.IO.StreamWriter(_outputFileName);
file.WriteLine(sb.ToString());
file.Close();
private static IEnumerable<XElement> FirstTextConsts(IEnumerable<MyClass> collection)
{
return collection.Select(r => new XElement("const",
new XAttribute("name", $"IDENTIFIER_{r.Id}"),
new XAttribute("translatable", "false"),
new XElement("text",
new XAttribute("lang","en"), r.Name)));
}
private static IEnumerable<XElement> SecondTextConsts(IEnumerable<MyClass> collection)
{
foreach (var obj in collection)
{
if (obj.someSelector)
yield return new XElement("const",
new XAttribute("name", $"IDENTIFIER_{r.Id}"),
new XAttribute("translatable", "false"),
new XElement("text",
new XAttribute("lang","en"), r.Name)));
if (obj.someOtherSelector)
yield return new XElement("const",
new XAttribute("name", $"IDENTIFIER_{r.Id}"),
new XAttribute("translatable", "true")
);
}
}
编辑2:
由于我确实需要XDocument的灵活性来构建可在不同级别返回IEnumerable的多级xml文档和辅助方法,因此我决定添加一个phony元素,然后在写入文件之前再次将其删除:
XDocument constsdocument = new XDocument(
new XElement("root",
new XComment($" Consts section generated on {DateTime.Now} "),
new XComment($" First group of constants. "),
FirstTextConsts(MyFirstCollection),
new XComment($" Refrigerant constants. "),
SecondTextConsts(MySecondCollection)
)
);
file.WriteLine(sb.ToString().Replace("<root>" + Environment.NewLine, "").Replace(Environment.NewLine + "</root>", ""));
解决方法:
<body bgcolor="white">