I have a strange problem with my customer - I am reading an XML document (actually an InfoPath document) with XmlSerializer
, modifying it, then writing out an XML document using the XmlSerializer
, and then add some processing instructions by using the XmlTextWriter
. All works well, and the resulting document is actually fully XML conform and can be read by InfoPath. One change that happens in the structure is however that the original document has all empty tags written in the form <A></A>
, and when my document is written, it becomes <A/>
. Actually exactly the same due to XML standards. But, my customer (a big company) apparently has some check/validation scripts with hardcoded <A></A>
, and they fail. He's is now upset, and is too lazy to change his scripts, and wants the <A></A>
notation! How can I setup XmlTextWriter
to do it?
答案 0 :(得分:5)
您可以通过向XmlSerializer
提供您自己的XmlWriter
后代来实现,这会覆盖WriteEndElement
method。默认情况下,此方法根据要输出的元素的内容生成一个空元素(<a />
)或一个结束元素(</a>
)。您可以更改行为以始终产生完整的结束元素。
public class MyXmlWriter : XmlTextWriter
{
// …constructors etc. omitted for the sake of simplicity…
public override void WriteEndElement()
{
// this should do the trick
WriteFullEndElement();
}
}
但是,还需要做更多的工作,例如此方法的Async
版本,但是原则上,应该像上面一样容易实现。我建议您研究XmlTextWriter.WriteEndElement
中的the source code,并得出一个更适合您情况的版本。
答案 1 :(得分:0)
老实说,我想如果您要使用内置的Serializer,那么最好进行查找/替换。看起来您无法覆盖标记的实际形式,至少我没有看到一种甚至可以覆盖某些方法的方法。
因此,我要检查一下标签是否为空,并输入"[[[EMPTYVALUE]]]"
之类的值,这样您最终会得到
<A>[[[EMPTYVALUE]]]</A>
然后生成您的XML,并在保存XML文件之前,将其转换为字符串,然后将"<A>[[[EMPTYVALUE]]]</A>"
替换为"<A></A>"
您可以只对<A/>
进行替换,但是我认为创建更大的字符串来替换是更安全的。