从XML文件中删除所有标记

时间:2012-05-15 20:01:55

标签: php asp.net xml xslt

我有一个大型XML文件,我想剥离所有标记并仅保留节点值。我希望每个节点值都在一个单独的行中。我怎么能这样做?

我可以使用免费软件来执行此操作,也可以使用PHP或ASP.NET代码。我也查看了XSLT选项。 RegEX可能太过分了。我探讨了查看simplexml_load_file()strip_tags()get_file_contents()的PHP选项,但失败了。

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- a comment -->
<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.90</price>
                <address>
                         <city>Melbourne </city>
                         <zip>01803 </zip>
                </address>
        <year>1985</year>
    </cd>
    <cd>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <country>UK</country>
        <company>CBS Records</company>
        <price>9.90</price>
        <year>1988</year>
    </cd>

</catalog>

编辑:这是我尝试过的,等等。

<?php

$xml = simplexml_load_file('myxml.xml');
echo strip_tags($xml);

?>

2 个答案:

答案 0 :(得分:5)

这应该是你做的:

<?php
$xml = file_get_contents('myxml.xml');
$xml = nl2br($xml);
echo strip_tags($xml,"<br>");
?>

您缺少换行符的原因是因为在XML中,它存储为纯文本换行符\n,而在以HTML格式显示时,您必须有明确的<br>换行符。因此,优秀的PHP人员为您做了一个名为nl2br()的便捷功能。

答案 1 :(得分:4)

这是一个简短的XSLT解决方案

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="text()">
  <br /><xsl:value-of select="concat(.,'&#xA;')"/>
 </xsl:template>
</xsl:stylesheet>

将此转换应用于提供的XML文档(适用于任何 XML文档):

<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.90</price>
        <address>
            <city>Melbourne </city>
            <zip>01803 </zip>
        </address>
        <year>1985</year>
    </cd>
    <cd>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <country>UK</country>
        <company>CBS Records</company>
        <price>9.90</price>
        <year>1988</year>
    </cd>
</catalog>

产生了想要的结果:

<br/>Empire Burlesque
<br/>Bob Dylan
<br/>USA
<br/>Columbia
<br/>10.90
<br/>Melbourne 
<br/>01803 
<br/>1985
<br/>Hide your heart
<br/>Bonnie Tyler
<br/>UK
<br/>CBS Records
<br/>9.90
<br/>1988

,浏览器将其显示为:


Empire Burlesque
鲍勃迪伦
美国
哥伦比亚
10.90
墨尔本
01803
1985
隐藏你的心
邦妮泰勒 英国

CBS记录
9.90
1988

相关问题