更改“XML 声明”,或选择“不带声明的 xml”部分

本文关键字:声明 不带声明的 xml 部分 XML 更改 选择 | 更新日期: 2023-09-27 18:32:09

我需要更改 by 文档的 xml 声明部分,或者只选择减去声明的数据。哪个更容易?

这是我的 xml 外观的示例:

<?xml version="1.0" encoding="utf-16"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master page-height="11in" page-width="8.5in" margin-top="0.50in" margin-left="0.8in" margin-right="0.8in" margin-bottom="0.25in" master-name="PageMaster">
            <fo:region-body border-style="none" border-width="thin" margin-top="0in" margin-left="0in" margin-right="0in" margin-bottom="0.25in"/>
            <fo:region-after border-style="none" border-width="thin" extent="0.25in"/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="PageMaster"/>
</fo:root>

我正在尝试将 xml 声明更改为:

<?xml version="1.0" encoding="iso-8859-1"?>

更改“XML 声明”,或选择“不带声明的 xml”部分

您是否正在尝试以编程方式更改 XML?如果是这样,您可以通过创建新XmlDeclaration并将其替换为前一个来执行此操作,如下所示:

XmlDeclaration xmlDeclaration;
xmlDeclaration = doc.CreateXmlDeclaration("1.0", "iso-8859-1", null);
doc.ReplaceChild(xmlDeclaration, doc.FirstChild);

您只需要确保文档的第一个子项是 Xml 声明。

使用 XSLT 可以轻松完成所需的"XML 声明更改"(不注释此更改是否是问题的正确解决方案):

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output indent="yes" encoding="ISO-8859-1"/>
 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

只需将此转换应用于提供的 XML 文档

<?xml version="1.0" encoding="utf-16"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master page-height="11in" page-width="8.5in" margin-top="0.50in" margin-left="0.8in" margin-right="0.8in" margin-bottom="0.25in" master-name="PageMaster">
            <fo:region-body border-style="none" border-width="thin" margin-top="0in" margin-left="0in" margin-right="0in" margin-bottom="0.25in"/>
            <fo:region-after border-style="none" border-width="thin" extent="0.25in"/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="PageMaster"/>
</fo:root>

并产生所需的结果

<?xml version="1.0" encoding="iso-8859-1"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master page-height="11in" page-width="8.5in" margin-top="0.50in" margin-left="0.8in" margin-right="0.8in" margin-bottom="0.25in" master-name="PageMaster">
            <fo:region-body border-style="none" border-width="thin" margin-top="0in" margin-left="0in" margin-right="0in" margin-bottom="0.25in" />
            <fo:region-after border-style="none" border-width="thin" extent="0.25in" />
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="PageMaster" />