我有以下xml,它将具有多个shareclass元素(很少会有AMFI代码,很少会有)。为了简单起见,我的共享类中的两个元素都为xml元素代码提供了AMFI代码。我想检索AMFI代码值(如果存在)及其共享类ID。现在,我无法正确循环以检索数据。我使用循环不正确或xml表现出这种方式吗?感谢您的帮助
export function getThis() {
return async function(dispatch, getState) {
const {data} = await axios.get('api/this/' + lienBuild);
return dispatch({type: "FETCH_THIS", data});
};
}
我的python代码是
<Feed xmlns="xxxxx" Version="1.01.021">
<AssetOverview Id="36113117">
<ShareClasses>
<ShareClass Id="68016655">
<Profile>
<CrossReferenceCodes>
<Code Type="RIC" Id="1000026">LP68016655</Code>
<Code Type="ISIN Code" Id="1001424">INF209K01264</Code>
<Code Type="ISIN Currency Class" Id="1005394">INF209K01264.INR</Code>
<Code Type="AMFI Code" Id="1010560">112088</Code>
<Code Type="Perm ID" Id="1036941">18068016655</Code>
</CrossReferenceCodes>
</Profile>
</ShareClass>
<ShareClass Id="68016656">
<Profile>
<CrossReferenceCodes>
<Code Type="RIC" Id="1000026">LP68016656</Code>
<Code Type="ISIN Code" Id="1001424">INF209K01256</Code>
<Code Type="ISIN Currency Class" Id="1005394">INF209K01256.INR</Code>
<Code Type="AMFI Code" Id="1010560">112087</Code>
<Code Type="Perm ID" Id="1036941">18068016656</Code>
</CrossReferenceCodes>
</Profile>
</ShareClass>
</ShareClasses>
</AssetOverview>
</Feed>
我的输出是
tree = ET.parse('test.xml')
namespace = get_namespace(tree.getroot())
root = tree.getroot()
for child in root:
for code1 in root.findall("./{}AssetOverview/{}ShareClasses/{}ShareClass/{}Profile/{}CrossReferenceCodes/{}Code".format(namespace,namespace,namespace,namespace,namespace,namespace)):
if 'AMFI Code' in code1.attrib.values():
print(code1.text)
for code in root.findall("./{}AssetOverview/{}ShareClasses/{}ShareClass".format(namespace,namespace,namespace)):
print(code.attrib['Id'])
所需的输出是
112088
68016655
68016656
112087
68016655
68016656
答案 0 :(得分:0)
代码可以简化很多。这样会产生所需的输出:
from xml.etree import ElementTree as ET
tree = ET.parse('test.xml')
for shareclass in tree.findall(".//{xxxxx}ShareClass"):
id = shareclass.get("Id")
amfi = shareclass.findtext(".//{xxxxx}Code[@Type='AMFI Code']")
print("{},{}".format(amfi, id))