我有一个看起来像这样的XDocument:
XDocument outputDocument = new XDocument(
new XElement("Document",
new XElement("Stuff")
)
);
当我打电话时
outputDocument.ToString()
输出到此:
<Document>
<Stuff />
</Document>
但是我希望它看起来像这样:
<Document>
<Stuff>
</Stuff>
</Document>
我知道第一个是正确的,但是我必须以这种方式输出它。有什么建议吗?
将每个空Value
的XElement
属性设置为专门的空字符串。
// Note: This will mutate the specified document.
private static void ForceTags(XDocument document)
{
foreach (XElement childElement in
from x in document.DescendantNodes().OfType<XElement>()
where x.IsEmpty
select x)
{
childElement.Value = string.Empty;
}
}
存在一个空标签时使用XNode.DeepEquals的问题,这是比较XML文档中所有XML元素的另一种方法(即使XML关闭标签不同,这也应该起作用)
public bool CompareXml()
{
var doc = @"
<ContactPersons>
<ContactPersonRole>General</ContactPersonRole>
<Person>
<Name>Aravind Kumar Eriventy</Name>
<Email/>
<Mobile>9052534488</Mobile>
</Person>
</ContactPersons>";
var doc1 = @"
<ContactPersons>
<ContactPersonRole>General</ContactPersonRole>
<Person>
<Name>Aravind Kumar Eriventy</Name>
<Email></Email>
<Mobile>9052534488</Mobile>
</Person>
</ContactPersons>";
return XmlDocCompare(XDocument.Parse(doc), XDocument.Parse(doc1));
}
private static bool XmlDocCompare(XDocument doc,XDocument doc1)
{
IntroduceClosingBracket(doc.Root);
IntroduceClosingBracket(doc1.Root);
return XNode.DeepEquals(doc1, doc);
}
private static void IntroduceClosingBracket(XElement element)
{
foreach (var descendant in element.DescendantsAndSelf())
{
if (descendant.IsEmpty)
{
descendant.SetValue(String.Empty);
}
}
}