更改Xml声明,或选择不带声明的xml部分

时间:2012-04-24 13:35:06

标签: c# .net xml xpath

我需要更改文档的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"?>

2 个答案:

答案 0 :(得分:7)

您是否尝试以编程方式更改XML?如果是这样,您可以创建新的XmlDeclaration并将其替换为前一个,如下所示:

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

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

答案 1 :(得分:0)

使用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" />