gpt4 book ai didi

java - 使用java将XML文件转换为CSV文件(具有多个元素值)

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:16 25 4
gpt4 key购买 nike

我正在将 XML 解析为 CSV。遇到一篇文章@Convert an XML file to CSV file using java并能够使用 data.xml 和 style.xsl 验证解决方案

基于 xml data.xml 构建,想知道如果某些元素存在多个值,则需要对 style.xsl 进行哪些更改。

例如,如果 data.xml 中有时存在多个操作系统

<?xml version="1.0"?>
<Sites>
<Site id="101" name="NY-01" location="New York">
<Hosts>
<Host id="1001">
<Host_Name>srv001001</Host_Name>
<IP_address>10.1.2.3</IP_address>
<OS>Windows</OS>
<Load_avg_1min>1.3</Load_avg_1min>
<Load_avg_5min>2.5</Load_avg_5min>
<Load_avg_15min>1.2</Load_avg_15min>
</Host>
<Host id="1002">
<Host_Name>srv001002</Host_Name>
<IP_address>10.1.2.4</IP_address>
<OS>Linux, Windows</OS>
<Load_avg_1min>1.4</Load_avg_1min>
<Load_avg_5min>2.5</Load_avg_5min>
<Load_avg_15min>1.2</Load_avg_15min>
</Host>
<Host id="1003">
<Host_Name>srv001003</Host_Name>
<IP_address>10.1.2.5</IP_address>
<OS>Linux</OS>
<Load_avg_1min>3.3</Load_avg_1min>
<Load_avg_5min>1.6</Load_avg_5min>
<Load_avg_15min>1.8</Load_avg_15min>
</Host>
<Host id="1004">
<Host_Name>srv001004</Host_Name>
<IP_address>10.1.2.6</IP_address>
<OS>Linux, NetBSD</OS>
<Load_avg_1min>2.3</Load_avg_1min>
<Load_avg_5min>4.5</Load_avg_5min>
<Load_avg_15min>4.2</Load_avg_15min>
</Host>

最佳答案

这样试试?

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="text" encoding="utf-8"/>

<xsl:template match="/">
<xsl:text>Host_Name,IP_address,OS,Load_avg_1min,Load_avg_5min,Load_avg_15min&#10;</xsl:text>
<xsl:for-each select="Sites/Site/Hosts/Host">
<xsl:value-of select="concat(Host_Name,',',IP_address,',&quot;',OS,'&quot;,',Load_avg_1min,',',Load_avg_5min,',',Load_avg_15min,'&#10;')"/>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>

或者,如果您愿意的话:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="text" encoding="utf-8"/>

<xsl:template match="/">
<xsl:text>Host_Name,IP_address,OS,Load_avg_1min,Load_avg_5min,Load_avg_15min&#10;</xsl:text>
<xsl:for-each select="Sites/Site/Hosts/Host">
<xsl:for-each select="*">
<xsl:text>"</xsl:text>
<xsl:value-of select="."/>
<xsl:text>"</xsl:text>
<xsl:if test="position()!=last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:for-each>
<xsl:if test="position()!=last()">
<xsl:text>&#10;</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>

请注意,两者都假设您的“字段”都不包含 " 引号。

关于java - 使用java将XML文件转换为CSV文件(具有多个元素值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23567059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com