好的,这就是我想要完成的。我有一个来自目录路径和安全组的 CSV 文件的 XML 文档。我想从具有匹配 Path 元素的节点中获取 Group 元素及其子元素,并将其复制到前一个节点。这是一个例子:
<root>
<Folder>
<Path>\\path\to\folder\_Shared Data\</Path>
<Group>
<Account>Shared_Data_RW</Account>
<FullName></FullName>
<AccountType>GROUP</AccountType>
<Permission>Modify</Permission>
</Group>
</Folder>
<Folder>
<Path>\\path\to\folder\_Shared Data\</Path>
<Group>
<Account>Shared_Data_RO</Account>
<FullName></FullName>
<AccountType>GROUP</AccountType>
<Permission>Read & Execute</Permission>
</Group>
</Folder>
</root>
好的,这就是现在的样子。请注意两个节点上的 Path 元素是如何相同的。我想要的是它看起来像这样:
<root>
<Folder>
<Path>\\path\to\folder\_Shared Data\</Path>
<Group>
<Account>Shared_Data_RW</Account>
<FullName></FullName>
<AccountType>GROUP</AccountType>
<Permission>Modify</Permission>
</Group>
<Group>
<Account>Shared_Data_RO</Account>
<FullName></FullName>
<AccountType>GROUP</AccountType>
<Permission>Read & Execute</Permission>
</Group>
</Folder>
</root>
第二个节点没有了,Group元素和它的子元素已经添加到前一个节点。
我对这类东西相当陌生,我对一般的一些编程和脚本编写很满意,但不确定实现此目的的最佳方法。我已经看到 XSLT 可能会做我正在寻找的事情,但我真正想要它做的是获取输入 XML 文件,进行更改,然后给我一个输出 XML 文件,以便我可以接受它并使用 jsTree 将其显示在树中的网页上。我还查看了用于处理 XML 的 Python 的 ElementTree,但我不太确定从哪里开始才能获得我正在寻找的结果。
最佳答案
这个转换:
<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:key name="kFolderByPath" match="Folder" use="Path"/>
<xsl:template match="/*">
<xsl:copy>
<xsl:apply-templates select=
"Folder[generate-id()=generate-id(key('kFolderByPath',Path)[1])]"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Folder">
<Folder>
<xsl:copy-of select=
"Path | key('kFolderByPath',Path)/*[not(self::Path)]"/>
</Folder>
</xsl:template>
</xsl:stylesheet>
应用于提供的 XML 文档(已针对格式良好性进行更正)时:
<root>
<Folder>
<Path>\\path\to\folder\_Shared Data\</Path>
<Group>
<Account>Shared_Data_RW</Account>
<FullName></FullName>
<AccountType>GROUP</AccountType>
<Permission>Modify</Permission>
</Group>
</Folder>
<Folder>
<Path>\\path\to\folder\_Shared Data\</Path>
<Group>
<Account>Shared_Data_RO</Account>
<FullName></FullName>
<AccountType>GROUP</AccountType>
<Permission>Read & Execute</Permission>
</Group>
</Folder>
</root>
产生想要的、正确的结果:
<root>
<Folder>
<Path>\\path\to\folder\_Shared Data\</Path>
<Group>
<Account>Shared_Data_RW</Account>
<FullName/>
<AccountType>GROUP</AccountType>
<Permission>Modify</Permission>
</Group>
<Group>
<Account>Shared_Data_RO</Account>
<FullName/>
<AccountType>GROUP</AccountType>
<Permission>Read & Execute</Permission>
</Group>
</Folder>
</root>
解释:
关于python - 当不同的子元素名称匹配时如何连接子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15147529/