[英]Add XElement to XML file with formatting and indenting
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,因為我需要保留所有空格(客戶需要)。 所需的輸出是在“根”的最后一個子元素之后放置 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);
}
理想情況下,您應該向您的客戶解釋這真的不重要。
但是,如果您真的需要處理空白,我會注意到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"));
請參閱此演示。
我的解決方案是在保存之前通過重新解析文檔來美化。
string content = XDocument.Parse(xDoc.ToString()).ToString();
File.WriteAllText(file, content, Encoding.UTF8);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.