4

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

我可以使用免费软件还是使用 PHP 或 ASP.NET 代码。我还查看了 XSLT 选项。RegEX 可能太多了。我探索了查看simplexml_load_file(),的 PHP 选项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);

?>
4

2 回答 2

5

这应该做你:

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

您缺少换行符的原因是因为在 XML 中,它存储为纯文本换行符\n,而当显示为 HTML 时,您必须有明确的<br>换行符。因此,优秀的 PHP 人员制作了一个方便的函数nl2br()来为您执行此操作。

于 2012-05-15T20:18:37.757 回答
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
Bob Dylan
USA
Columbia
10.90
Melbourne
01803
1985
隐藏你的心
Bonnie Tyler
UK
CBS Records
9.90
1988

于 2012-05-16T03:01:36.487 回答