我如何保存所有与XML格式的XDocument? [英] How do I preserve all XML formatting with XDocument?
问题描述
我想在一个XML配置文件读取,做了几个调整(找到并删除或添加一个元素),并再次保存它。我想这编辑是作为非侵入性越好,因为该文件将源代码控制之下,我不想改变无关紧要导致合并冲突等,这大致就是我有:
I'm trying to read in an XML configuration file, do a few tweaks (finding and removing or adding an element) and save it again. I want this edit to be as non-intrusive as possible since the file will be under source control and I don't want inconsequential changes to cause merge conflicts, etc. This is roughly what I've got:
XDocument configDoc = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
// modifications to configDoc here
configDoc.Save(fileName, SaveOptions.DisableFormatting);
还有,这里弹出了几个问题:
There's a few problems that pop up here:
-
编码=UTF-8
被添加到XML声明。 -
<标签ATTR =VAL/>
被更改为<标签ATTR =VAL/>
- 跨越不同的线被流传了可读性的属性得到全押在一行。
encoding="utf-8"
gets added to the xml declaration.<tag attr="val"/>
gets changed to<tag attr="val" />
- Attributes that were spread across separate lines for readability get pushed all on to one line.
有什么办法不那么侵扰用的XDocument或将我只是尝试做字符串编辑得到我想要什么?
Is there any way to be less intrusive with XDocument or will I have to just try and do string editing to get what I want?
推荐答案
本的LINQ to XML对象模型不存储解析元素是否被标记为<富/>
或<富/> ;
因此节省回来这样的信息时,会丢失。如果你想保证一定的格式,那么你可以扩展一个的XmlWriter实现并覆盖其的 http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.writeendelement.aspx 但这样你也不会保留输入格式,而你会再写出所有空元素<富/方式>
或你在你的方法实施的任何格式
The LINQ to XML object model does not store whether an element parsed is marked up as <foo/>
or <foo />
so when saving back such information is lost. If you want to ensure a certain format then you could extend an XmlWriter implementation and override its http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.writeendelement.aspx but that way you would also not preserve the input format, rather you would then write out any empty elements as <foo/>
or whatever format you implement in your method.
有在加载文件时可能发生,比如其它变化
There are other changes that can happen, for instance when loading the file
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xhtml="http://www.w3.org/1999/xhtml">
<head>
<title>Example</title>
</head>
<body>
<h1>Example</h1>
</body>
</html>
和保存回结果是
<xhtml:html xmlns="http://www.w3.org/1999/xhtml" xmlns:xhtml="http://www.w3.org/1999/xhtml">
<xhtml:head>
<xhtml:title>Example</xhtml:title>
</xhtml:head>
<xhtml:body>
<xhtml:h1>Example</xhtml:h1>
</xhtml:body>
</xhtml:html>
所以不要指望加载/带的XDocument /的XElement保存时要保留标记的详细信息。
so don't expect markup details to be preserved when loading/saving with XDocument/XElement.
这篇关于我如何保存所有与XML格式的XDocument?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!