有没有办法自定义XmlWriter的序列化输出?

问题描述 投票:0回答:1

我正在使用以下内容来序列化我的 XML 文档:

        XmlWriter xw = XmlWriter.Create(sbXmlDoc, new XmlWriterSettings {
            Indent = true,
            IndentChars = "  ",
            OmitXmlDeclaration = true
        });

这会创建一个

System.Xml.XmlWellFormedWriter
的实例,由于某种原因它是
internal
所以我无法扩展/覆盖它。 它输出空元素,如
<element />
而不是
<element/>
,放入额外的空格。有什么方法可以自定义输出,以便删除尾部斜杠之前的额外空格? 我知道
XmlTextWriter
但现在似乎建议使用
XmlWriter.Create()
来代替。

c# xml serialization
1个回答
0
投票

这是使用 Saxon 和 XSLT 3.0 的通用解决方案

输入XML

<root>
   <city>Miami</city>
   <state />
</root>

XSLT 3.0

<?xml version="1.0"?>
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" expand-text="yes">
   <xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="no"/>
   <xsl:strip-space elements="*"/>

   <xsl:mode on-no-match="shallow-copy"/>

</xsl:stylesheet>

输出XML

<?xml version="1.0" encoding="utf-8"?>
<root>
   <city>Miami</city>
   <state/>
</root>

c#

void Main()
{
    const string XSLTFILE = @"c:\Saxon-HE 10\IdentityTransform.xslt";
    const string INFILE = @"c:\Saxon-HE 10\input.xml";
    const string OUTFILE = @"c:\Saxon-HE 10\output.xml";

    // Create a Processor instance.
    Processor processor = new Processor();

    // Load the source document
    XdmNode input = processor.NewDocumentBuilder().Build(new Uri(INFILE));

    // Create a transformer for the stylesheet.
    Xslt30Transformer transformer = processor.NewXsltCompiler().Compile(new Uri(XSLTFILE)).Load30();

    // Create a serializer, with output to the standard output stream
    Serializer serializer = processor.NewSerializer();
    serializer.SetOutputStream(new FileStream(OUTFILE, FileMode.Create, FileAccess.Write));

    // Transform the source XML and serialize the result document
    transformer.ApplyTemplates(input, serializer);
    
    Console.WriteLine("Output written to '{0}'",  OUTFILE);
}
© www.soinside.com 2019 - 2024. All rights reserved.