首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在xml文件中取消行的缩进

如何在xml文件中取消行的缩进
EN

Stack Overflow用户
提问于 2010-11-18 04:16:18
回答 5查看 647关注 0票数 0

考虑以下XML文件内容:

代码语言:javascript
运行
复制
<catalog>
  <cd>
        <title>Red</title>
        <artist>The Communards</artist>
  </cd>
  <cd>
        <title>Unchain my heart</title>
        <artist>Joe Cocker</artist>
  </cd>
</catalog>

如何使用任何现有工具或XSLT获得以下内容?

代码语言:javascript
运行
复制
<catalog>
  <cd><title>Red</title><artist>The Communards</artist></cd>
  <cd><title>Unchain my heart</title><artist>Joe Cocker</artist></cd>
</catalog>

我想做这个转换,因为我想快速地从xml文件中删除一些记录(在本例中是'cd‘)。使用单行格式会对我有所帮助。

谢谢!

EN

回答 5

Stack Overflow用户

发布于 2010-11-18 04:44:00

我想做这个转换,因为我想快速地从

文件中删除一些记录(在本例中是'cd‘)。使用单行格式会对我有所帮助。

我很抱歉,但这是一个错误的方法。您希望使用XSLT来操作文档中的空格,这样可以更容易地使用...不是XSLT的东西?首先删除XSLT中不需要的代码行!

基本示例(未经测试,但99%确定这将满足给定的要求):

代码语言:javascript
运行
复制
<xsl:stylesheet version="1.0">

  <!-- this is called the identity transform - it will copy the input wholesale -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <!-- this template will provide the exception case for "cd" nodes and effectively remove them -->
  <xsl:template match="cd">
    <!-- do nothing with it! -->
  </xsl:template>

</xsl:stylesheet>
票数 4
EN

Stack Overflow用户

发布于 2010-11-18 05:06:27

奇怪的重复(不是语义差异)...此样式表:

代码语言:javascript
运行
复制
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="no" omit-xml-declaration="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="@*|node()" name="identity">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="cd">
        <xsl:text>&#xA;&#x9;</xsl:text>
        <xsl:call-template name="identity"/>
        <xsl:value-of select="substring('&#xA;', 1 div (position()=last()))"/>
    </xsl:template>
</xsl:stylesheet>

输出:

代码语言:javascript
运行
复制
<catalog>
    <cd><title>Red</title><artist>The Communards</artist></cd>
    <cd><title>Unchain my heart</title><artist>Joe Cocker</artist></cd>
</catalog>

注意:标识规则,xsl:cd -space(修剪所有文本节点),为cd添加新行和制表符,为最后一行添加新行。

票数 2
EN

Stack Overflow用户

发布于 2010-11-18 04:34:16

测试结果:

这里有一个解决方案:

代码语言:javascript
运行
复制
<xsl:stylesheet 
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output indent="no" method="xml"/>
<xsl:strip-space elements="cd title artist"/>

<xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>

</xsl:stylesheet>

关键是要确保输出不会自动缩进,然后指定哪些元素应该删除空格,比如cdtitleartist

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4208749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档