我正在更新 xml 文件,并希望使用 ET.register_namespace
保留具有相同 URI 但不同 anchor 标记的多个命名空间
以下代码是我尝试过的:
ET.register_namespace('', "http://oval.mitre.org/XMLSchema/oval-definitions-5")
ET.register_namespace('', "http://oval.mitre.org/XMLSchema/oval-definitions-5#windows")
ET.register_namespace('', "http://oval.mitre.org/XMLSchema/oval-definitions-5#independent")
ns = "{http://oval.mitre.org/XMLSchema/oval-definitions-5}"
f = open ("def_ex.xml","ra")
tree = ET.parse(f)
root = tree.getroot()
for defn in root.iter('%stag' %ns):
if "patch" in defn.get("class"): #pick id attrib where class attrib is "patch"
print defn.get("id")
mirr_def = copy.deepcopy(defn)
defn.append(mirr_def)
tree.write("def_ex.xml")
exit()
但问题是 third
命名空间覆盖了 one
和 two
,如以下代码输出所示:
<ns0:tag>
.......
.......
</ns0:tag>
<ns1:tag1>
........
........
</ns1:tag1>
<tag2>
......
......
</tag2>
我的最后一个问题是,当存在具有相同 URI 的不同“ anchor 标记”时,如何保留所有 namespace 而不互相覆盖?
更新:def_ex.xml
<oval_definitions xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oval="http://oval.mitre.org/XMLSchema/oval-common-5" xmlns:oval-def="http://oval.mitre.org/XMLSchema/oval-definitions-5" xmlns:windows-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#windows" xmlns:independent-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#independent" xsi:schemaLocation=" http://oval.mitre.org/XMLSchema/oval-definitions-5#windows windows-definitions-schema.xsd http://oval.mitre.org/XMLSchema/oval-definitions-5#independent independent-definitions-schema.xsd http://oval.mitre.org/XMLSchema/oval-definitions-5 oval-definitions-schema.xsd http://oval.mitre.org/XMLSchema/oval-common-5 oval-common-schema.xsd">
<tag id="oval:def:1" class="inventory">
...........
...........
...........
</tag>
<tag1 xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5#windows" id="oval:tst:1" version="1">
............
............
</tag1>
<tag2 xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5#independent" id="oval:tst:2" version="1">
............
............
</tag2>
</oval_definitions>
最佳答案
如@mu 無已经说过,您将无法使用 register_namespace 实现您想要的目标,它明确防止出现重复的前缀。
我不确定您想要做的是否是合法的 XML 或者是否受库支持,但可能实现您想要的效果的一种方法是实现 behaviour直接register_namespace:
xml.etree.ElementTree._namespace_map[uri] = prefix # Replace uri and prefix.
作为一个函数(修改自原始Python库source code):
import re
import xml.etree.ElementTree
def register_namespace(prefix, uri):
if re.match("ns\d+$", prefix):
raise ValueError("Prefix format reserved for internal use")
xml.etree.ElementTree._namespace_map[uri] = prefix
我不建议这样做,因为它可能会以意想不到的方式破坏其他地方的库。
免责声明:我的代码尚未经过测试。
关于python - 如何对具有不同 "anchor tag"的同一 URL 多次使用 register_namespace ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25544139/