如何将同一类型的多个xml节点合并到一个节点中?

2024-09-21 03:29:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个相当大的xml文档,看起来像:

<products>
  <product>
    <id>1</id>
    <other>y</other>
    <notarget>x</notarget>
    <target>num1</target>
    <target>num2</target>
    <target>num3</target>
  </product>
</products>

但我需要它看起来像:

^{pr2}$

我对xml没有太多的经验,所以我甚至不知道应该使用什么技术来检查文件以进行这些更改。可以有多个产品,但此示例只有一个。我使用python,但也可以使用shell。在


Tags: 文件文档idtarget经验xmlproduct技术
3条回答

需要从一个XML转换到另一个XML是生成XSLT的原因。在

所以,这是一个纯的解决方案,在中使用

在文件.xml:

<products>
  <product>
    <id>1</id>
    <other>y</other>
    <notarget>x</notarget>
    <target>num1</target>
    <target>num2</target>
    <target>num3</target>
  </product>
</products>

xsl文件:

^{pr2}$

命令行:

$ java -cp 'saxon9he.jar' net.sf.saxon.Transform -xsl:xsl -s:file.xml '!indent=yes'

输出:

<?xml version="1.0" encoding="UTF-8"?>
<products>
  <product>
    <id>1</id>
    <other>y</other>
    <notarget>x</notarget>
    <target>num1,num2,num3</target>
  </product>
</products>

检查http://saxon.sourceforge.net/saxon6.5/using-xsl.html

对于任何希望在Mac OS上执行此操作的人,您需要安装一个JDK from Oracle,然后您可以通过homebrew从终端安装Saxon:

brew install saxon

在终端中,我使用的命令是:

^{pr2}$

工作起来很有魅力!在

这听起来确实像是xslt transformation的工作,但这里有一个特定于python的方法。在

每查找一个元素。在循环目标之后,将一个新的target项附加到product中。在

使用^{}实现:

from lxml import etree

data = """
<products>
  <product>
    <id>1</id>
    <other>y</other>
    <notarget>x</notarget>
    <target>num1</target>
    <target>num2</target>
    <target>num3</target>
  </product>
</products>
"""

root = etree.fromstring(data)
for product in root.iterfind('product'):
    text = []
    for target in product.iterfind('target'):
        text.append(target.text)
        product.remove(target)

    if text:
        new_target = etree.Element('target')
        new_target.text = ','.join(text)
        product.append(new_target)

print etree.tostring(root)

印刷品:

^{pr2}$

如您所见,它适用于您提供的输入。在

相关问题 更多 >

    热门问题