我有一个看起来像这样的XDocument:
XDocument outputDocument = new XDocument(
new XElement("Document",
new XElement("Stuff")
)
);
当我打电话给
outputDocument.ToString()
输出结果如下:
<Document>
<Stuff />
</Document>
但我希望它看起来像这样:
<Document>
<Stuff>
</Stuff>
</Document>
我意识到第一个是正确的,但我需要这样输出它。有什么建议吗?
发布于 2010-03-17 08:42:04
将每个空XElement
的Value
属性专门设置为空字符串。
// 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;
}
}
发布于 2020-02-23 16:22:30
当存在空标记时使用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);
}
}
}
https://stackoverflow.com/questions/2459138
复制相似问题