【问题标题】:How to parse xml using python [duplicate]如何使用python解析xml [重复]
【发布时间】:2016-09-30 01:28:52
【问题描述】:

我有以下 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    cq:lastReplicated="{Date}2016-03-02T15:23:40.679-05:00"
    cq:lastReplicatedBy="XXXXt"
    cq:lastReplicationAction="Activate"
    jcr:description="Procedure"
    jcr:mixinTypes="[cq:ReplicationStatus]"
    jcr:primaryType="cq:Tag"
    jcr:title="Lung Volume Reduction Surgery"
    sling:resourceType="cq/tagging/components/tag"/>

我正在尝试使用 ElementTree 解析 XML 文件,但我无法提取标签 jcr:title 下的“Lung Volume Reduction Surgery”。

我已经尝试过 BeatifulSoup 、 Regex 和 ElementTree 但无法做到

以下是我用于元素树的代码:

import xml.etree.ElementTree as ET
xml="Actual xml document"
xml.find('./root').attrib['title']

我是 XML 解析的初学者 .. 现在在这个 XML 文件上花费了 3 个多小时,但无法解析 jcr:title 的值任何帮助将不胜感激

【问题讨论】:

  • 你需要使用命名空间

标签: python xml beautifulsoup elementtree parsexml


【解决方案1】:

这是一种方法,使用 xml.etree.ElementTree

from xml.etree import ElementTree as ET

tree = ET.parse('input.xml')
root = tree.getroot()

jcr_namespace = "http://www.jcp.org/jcr/1.0"

print root.attrib[ET.QName(jcr_namespace, 'title')]

【讨论】:

    猜你喜欢
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多