使用格式和缩进将XElement添加到XML文件

时间:2018-02-20 13:12:48

标签: c# xml linq-to-xml xelement

XML

源XML

<!-- The comment -->
<Root xmlns="http://www.namespace.com">
    <FirstElement>
    </FirstElement>

    <SecondElement>
    </SecondElement>
</Root>

所需的XML

<!-- The comment -->
<Root xmlns="http://www.namespace.com">
    <FirstElement>
    </FirstElement>

    <SecondElement>
    </SecondElement>

    <ThirdElement>
        <FourthElement>thevalue</FourthElement>
    </ThirdElement>
</Root>

现在我的输出XML是

<!-- The comment -->
<Root xmlns="http://www.namespace.com">
    <FirstElement>
    </FirstElement>

    <SecondElement>
    </SecondElement><ThirdElement><FourthElement>thevalue</FourthElement></ThirdElement>
</Root>

请注意,我需要使用LoadOptions.PreserveWhitespace加载XML,因为我需要保留所有空格(客户需要)。 所需的输出是在&#34; root&#34;的最后一个子元素之后放置2个换行符。并添加适当的缩进

<ThirdElement>
    <FourthElement>thevalue</FourthElement>
</ThirdElement>

任何想法如何实现这一点?

代码

var xDoc = XDocument.Load(sourceXml, LoadOptions.PreserveWhitespace); //need to preserve all whitespaces
var mgr = new XmlNamespaceManager(new NameTable());
var ns = xDoc.Root.GetDefaultNamespace();
mgr.AddNamespace("ns", ns.NamespaceName);

if (xDoc.Root.HasElements)
{
    xDoc.Root.Elements().Last().AddAfterSelf(new XElement(ns + "ThirdElement", new XElement(ns + "FourthElement", "thevalue")));

    using (var xw = XmlWriter.Create(outputXml, new XmlWriterSettings() { OmitXmlDeclaration = true })) //omit xml declaration
        xDoc.Save(xw);
}

2 个答案:

答案 0 :(得分:3)

理想情况下,您应该向您的客户解释这真的不重要。

但是,如果你真的需要乱七八糟的空格,我注意到XText就是你需要的。这是另一个代表文本节点的XObject,可以作为内容的一部分穿插。这可能是一种比字符串操作更好的方法。

例如:

doc.Root.Add(
    new XText("\n\t"),
    new XElement(ns + "ThirdElement",
        new XText("\n\t\t"),
        new XElement(ns + "FourthElement", "thevalue"),
        new XText("\n\t")),
    new XText("\n"));

请参阅this demo

答案 1 :(得分:0)

我的解决方案是通过重新解析文档在保存之前将其美化。

string content = XDocument.Parse(xDoc.ToString()).ToString();
File.WriteAllText(file, content, Encoding.UTF8);