从所有 Xml 节点值中删除空格 [英] Remove white space from all Xml Node Values
问题描述
是否可以在不遍历每个节点的情况下从 XML 节点值中修剪前导和尾随空格.
Is there anyway to trim leading and trailing white spaces from XML node values without looping through each node.
例如
将变为
以下代码执行此操作,但我不想遍历每个会影响性能的节点:
The following code does this but I don't want to loop through each node which would be a performance hit:
if (node.ChildNodes.Count == 0)
node.InnerText = node.InnerText.Trim();
else
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
TrimLeadingOrTrailingSpacesFromNodeValue(node.ChildNodes[i]);
}
}
有更好的方法吗?LoadOptions.PreserveWhitespace
不是我要找的,我需要修剪 XML 节点中的值.
Is there a better way? The LoadOptions.PreserveWhitespace
is not what I am looking for, I need to trim the values in the XML nodes.
推荐答案
这是我为 Xml.Linq.XElement
编写的扩展,但我不确定性能.
Here is an extension I wrote for Xml.Linq.XElement
but I am not sure about performance.
我确实找到了这个创建 xml 文档时 XmlDocument 与 XElement 的性能比较显示使用 XElement 提高了 6 到 10 倍.我不确定这些结果的有效性,并且它是创建文档与迭代元素和更新值,因此要考虑它的价值.
I did find this performance comparison of XmlDocument vs XElement when creating xml documents that shows 6x - 10x improvement using XElement. I am not sure how valid those results are AND it is creating a document vs. iterating over elements and updating values so take it for what it's worth.
无论如何,我想我会分享一个替代方案.也许以后我自己或其他人会有动力分析这种特定用法的性能(去除空格).
Either way, thought I would share an alternative. Maybe later myself or someone else will have motivation to analyze the performance of this particular usage (removing whitespace).
public static class XElementExtensions
{
/// <summary>
/// Trims whitespace from the xml node values.
/// DOES NOT trim whitespace outside of values, can use PreserveWhitespace LoadOption when parsing for that.
/// </summary>
/// <param name="element"></param>
public static void TrimWhiteSpaceFromValues(this XElement element)
{
foreach (var descendent in element.Descendants())
{
if (!descendent.HasElements)
{
descendent.SetValue(descendent.Value.Trim());
}
else
{
descendent.TrimWhiteSpaceFromValues();
}
}
}
}
示例用法:
XElement element = XElement.Parse(xmlDocString);
element.TrimWhiteSpaceFromValues();
这篇关于从所有 Xml 节点值中删除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!