从XML文件中删除所有标签

4
我有一个很大的XML文件,我想去掉所有标签,只保留节点值。我希望每个节点值在单独的一行上。如何实现?
我可以使用免费软件来实现它,或者使用PHP或ASP.NET代码来实现。我也看了XSLT选项,但这可能对于RegEX来说太过复杂了。我也尝试了PHP选项,查看了simplexml_load_file(), strip_tags(), get_file_contents()等函数,但都没有成功。
<?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);

?>

strip_tags() 应该可以工作。你能否发布一下你尝试使用它的方式? - Connor Peet
我感觉这个问题有点像另一个问题,如何解析标签https://dev59.com/X3I-5IYBdhLWcg3wq6do -- 我只想说要小心。 - Kristian
@ConnorPeet添加了“strip_tags”的代码片段。我没有从中得到任何输出,因为$xml基本上是一个数组。 - TheTechGuy
这是因为你在浏览器中查看它。通过 nl2br(),你会看到它们都在单独的行上。 - DaveRandom
研究一下使用XSL转换。你应该能够轻松地格式化XML数据。http://php.net/manual/en/book.xsl.php - Ed Manet
显示剩余4条评论
2个回答

5
这应该能帮到你:

这是需要的内容:

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

你缺少换行是因为在XML中,它以纯文本的方式存储换行符\n,而当显示为 HTML 时,您必须具有显式的 <br> 换行。由于这个原因,好心的 PHP 开发者创建了一个非常方便的函数叫做 nl2br() 来帮助你实现这一功能。

顺便说一句,我想要一个可以操作每一行的代码。我需要在节点之前添加一些内容并在之后添加一些内容。 - TheTechGuy

5

这里有一个简短而简单的 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

并且它由浏览器显示为:


帝国脱衣舞厅
鲍勃·迪伦
美国
哥伦比亚
10.90
墨尔本
01803
1985年
隐藏你的心
邦妮·泰勒
英国
CBS唱片公司
9.90
1988年


谢谢!这也对我有帮助。顺便说一下,我并没有在寻找什么,只是想去掉标签。 - TheTechGuy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接