我有一堆与空格处理有关的问题XmlDocument
。请参阅下面示例中的编号注释。
在混合模式下,所有空格不应该很重要吗?为什么标签之间的空间
a
不显着?虽然我知道实际的空白元素仍然是
XmlWhitespace
,但如何将这些空间标准化为XmlSignificantWhitespace
节点?Normalize()
不起作用。我唯一的选择是手动吗?
这是我的测试用例:
private static void Main()
{
// 1. Shouldn't all whitespace be significant in mixed mode? Why the space between the a tags is not significant?
var doc = new XmlDocument
{
InnerXml = "<root>test1 <a>test2</a> <a>test3</a></root>",
};
PrintDoc(doc);
// 2.a. While I understand that the actual whitespace element is still XmlWhitespace, how do I normalize these spaces into XmlSignificantWhitespaces?
doc.DocumentElement.RemoveAll();
doc.DocumentElement.SetAttribute("xml:space", "preserve");
var fragment = doc.CreateDocumentFragment();
fragment.InnerXml = "test1 <a>test2</a> <a>test3</a>";
doc.DocumentElement.PrependChild(fragment);
PrintDoc(doc);
// 2.b. Normalize doesn't work
doc.Normalize();
PrintDoc(doc);
// 3.a. Manual normalization does work, is there a better way?
doc.DocumentElement.RemoveAllAttributes();
var whitespaces = doc.DocumentElement.ChildNodes.Cast<XmlNode>()
.OfType<XmlWhitespace>()
.ToList();
foreach (var whitespace in whitespaces)
{
var significant = doc.CreateSignificantWhitespace(whitespace.Value);
doc.DocumentElement.ReplaceChild(significant, whitespace);
}
PrintDoc(doc);
// 3.b. Reading from string also works
doc.InnerXml = "<root xml:space=\"preserve\">test1 <a>test2</a> <a>test3</a></root>";
PrintDoc(doc);
}
private static void PrintDoc(XmlDocument doc)
{
var nodes = doc.DocumentElement.ChildNodes.Cast<XmlNode>().ToList();
var whitespace = nodes.OfType<XmlWhitespace>().Count();
var significantWhitespace = nodes.OfType<XmlSignificantWhitespace>().Count();
Console.WriteLine($"Xml: {doc.InnerXml}\nwhitespace: {whitespace}\nsignificant whitespace: {significantWhitespace}\n");
}
输出如下:
Xml: <root>test1 <a>test2</a><a>test3</a></root>
whitespace: 0
significant whitespace: 0
Xml: <root xml:space="preserve">test1 <a>test2</a> <a>test3</a></root>
whitespace: 1
significant whitespace: 0
Xml: <root xml:space="preserve">test1 <a>test2</a> <a>test3</a></root>
whitespace: 1
significant whitespace: 0
Xml: <root>test1 <a>test2</a> <a>test3</a></root>
whitespace: 0
significant whitespace: 1
Xml: <root xml:space="preserve">test1 <a>test2</a> <a>test3</a></root>
whitespace: 0
significant whitespace: 1