微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

CodeGo.net>我如何建立一个XML部分,并保存到文件(本身不是有效的XML文档)

我正在尝试构建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();

编辑1:
创建文档时调用的两种方法(原则上):

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

解决方法:


502 Bad Gateway
<body bgcolor="white">

502 Bad Gateway

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。