检查 XML 元素是否等于另一个 XML 元素,忽略空值 [英] Check if XML element equals another XML element, ignoring empty values
本文介绍了检查 XML 元素是否等于另一个 XML 元素,忽略空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在检查字符串给出的两个 XML 元素是否与此方法相等:
I'm checking if two XML elements given by string are equal with this method:
private static bool XmlEquals(string s1, string s2)
{
return XNode.DeepEquals(XElement.Parse(s1), XElement.Parse(s2));
}
除非其中一个元素有开始和结束标签,而另一个有这样的结束标签,否则这项工作是可行的:
This work unless one of the elements has opening and closing tags and the other has a closed tag like this:
<MyElement SomeAttribute="some value" />
<MyElement SomeAttribute="some value"></MyElement>
我能否以某种方式比较两个 XML 元素,使上述情况被认为相等?
Can I somehow compare two XML elements in a way, that the above case is considered equal?
推荐答案
解决这个特定问题的直接方法是 明确引入右括号:
Straightforward way to solve this particular problem is to introduce closing brackets explicitly:
private static bool XmlEquals(string s1, string s2)
{
var firstElement = XElement.Parse(s1);
var secondElement = XElement.Parse(s2);
IntroduceClosingBracket(firstElement);
IntroduceClosingBracket(secondElement);
return XNode.DeepEquals(firstElement, secondElement);
}
private static void IntroduceClosingBracket(XElement element)
{
foreach (var descendant in element.DescendantsAndSelf())
{
if (descendant.IsEmpty)
{
descendant.SetValue(String.Empty);
}
}
}
不过,遍历所有后代可能会导致性能下降.
Loop through all descendants may cause a performance hit, though.
这篇关于检查 XML 元素是否等于另一个 XML 元素,忽略空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文