如何將這個 XML 檔案中的兩條不同資訊連接在一起?
# data
xml1 = ('''<?xml version="1.0" encoding="utf-8"?>
<TopologyDefinition xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RSkus>
<RSku ID="V1" Deprecated="true" Owner="Unknown" Generation="1">
<Devices>
<Device ID="1" SkuID="Switch" Role="xD" />
</Devices>
<Blades>
<Blade ID="{1-20}" SkuID="SBlade" />
</Blades>
<Interfaces>
<Interface ID="COM" HardwareID="NS1" SlotID="COM1" Type="serial" />
<Interface ID="LINK" HardwareID="TS1" SlotID="UPLINK_1" Type="serial" />
</Interfaces>
<Wires>
<WireGroup Type="network">
<Wire LocationA="NS1" SlotA="{1-20}" LocationB="{1-20}" SlotB="NIC1" />
</WireGroup>
<WireGroup Type="serial">
<Wire LocationA="TS1" SlotA="{7001-7020}" LocationB="{1-20}" SlotB="COM1" />
</WireGroup>
</Wires>
</RSku>
</RSkus>
</TopologyDefinition>
''')
雖然在下面的例子中這是一個單一的案例并且微不足道;如果我在完整檔案上運行以下命令,我會得到不匹配的形狀,因此無法輕松連接。
如何提取 XML 資訊,以便對于每一行,我都可以獲得所有RSku資訊以及它的Blade資訊。每個 xpath 都不包含可以讓我將其加入另一個 xpath 的資訊,以便我可以組合這些資訊。
# how to have them joined?
pd.read_xml(xml1, xpath = ".//RSku")
pd.read_xml(xml1, xpath = ".//Blade")
# expected
pd.concat([pd.read_xml(xml1, xpath = ".//RSku"), pd.read_xml(xml1, xpath = ".//Blade")], axis=1)
uj5u.com熱心網友回復:
考慮使用 XSLT 轉換 XML,方法是使用您需要的資訊來展平檔案。具體來說,僅使用軸檢索Blade屬性descendant::*,并使用軸檢索相應的RSku屬性ancestor::*。Python' lxml(默認決議器pandas.read_xml)可以運行 XSLT 1.0 腳本。
下面的 XSLT<xsl:for-each>用于前綴RSku_和Blade_屬性名稱,因為它們共享相同的屬性,例如ID. 否則模板會少得多羅嗦。
import pandas as pd
xml1 = ...
xsl = ('''<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/TopologyDefinition">
<root>
<xsl:apply-templates select="descendant::Blade"/>
</root>
</xsl:template>
<xsl:template match="Blade">
<data>
<xsl:for-each select="ancestor::RSku/@*">
<xsl:attribute name="{concat('RSku_', name())}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:for-each>
<xsl:for-each select="@*">
<xsl:attribute name="{concat('Blade_', name())}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:for-each>
</data>
</xsl:template>
</xsl:stylesheet>''')
blades_df = pd.read xml(xml1, stylesheet=xsl)
Online XSLT Demo
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/525008.html
標籤:Python熊猫xml
上一篇:為什么我在RealtiveLayout.setBackgroundColor上得到一個空物件參考,盡管我已經初始化了它
