首页 > 解决方案 > 如果有子节点,如何使用正确的样式表将 XML 转换为 CSV

问题描述

我在.xsl为以下xml代码创建文件时遇到问题。我想把它变成一个csv文件

XML:

<?xml version="1.0" encoding="utf-8"?>
<info infoID="Info_ABC">
  <descriptions>
    <description descriptionId="1" descriptionName="Test1">
      <functions>
        <function functionId="123">
          <programs>
            <program programName="Xml2Csv">
              <objects>
                <object objectId="111" objectLevel="Green" status="Yes"/>
                <object objectId="222" objectLevel="Blue" status="No"/>
                <object objectId="333" objectLevel="Red" status="Maybe"/>
              </objects> 
              <objects2>
                <object objectId="444" objectLevel="Yellow" status="Yes"/>
                <object objectId="555" objectLevel="Purple" status="Yes"/>
              </objects2>
            </program>
          </programs>
        </function>
        <function functionId="456">
          <programs>
            <program programName="Xml5Csv">
              <objects>
                <object objectId="666" objectLevel="Green" status="Yes"/>
                <object objectId="777" objectLevel="Blue" status="No"/>
                <object objectId="888" objectLevel="Red" status="Maybe"/>
              </objects> 
              <objects2>
                <object objectId="999" objectLevel="Yellow" status="Yes"/>
                <object objectId="897" objectLevel="Purple" status="Yes"/>
              </objects2>
            </program>
          </programs>
        </function>
      </functions>
    </description>
  </descriptions>
</info>

我希望我csv看起来像这样

Header:
info_ABC,description_id,description_name,function_id,program_name,objectId,objectLevel,status

Data:
info_ABC,1,Test1,123,Xml2CSV,111,Green,Yes
info_ABC,1,Test1,123,Xml2CSV,222,Blue,No
info_ABC,1,Test1,123,Xml2CSV,333,Red,Maybe
info_ABC,1,Test1,123,Xml2CSV,444,Yellow,Yes
info_ABC,1,Test1,123,Xml2CSV,555,Purple,Yes
info_ABC,1,Test1,456,Xml5CSV,666,Green,Yes
info_ABC,1,Test1,123,Xml2CSV,777,Blue,No
info_ABC,1,Test1,123,Xml2CSV,888,Red,Maybe
info_ABC,1,Test1,123,Xml2CSV,999,Yellow,Yes
info_ABC,1,Test1,123,Xml2CSV,897,Purple,Yes

标签: javaxmlcsvxslt

解决方案


使用遍历叶子<object>元素<xsl:for-each select="//object">,并在循环中使用例如访问祖先属性,<xsl:value-of select="ancestor::function/@functionId"/>

(顺便说一句,你没有说你对任务的哪一部分有困难,所以我不得不猜测。)


推荐阅读