gpt4 book ai didi

python - 如何使用任何脚本(python/shell)自动插入和解析xml元素?

转载 作者:行者123 更新时间:2023-12-01 01:47:27 24 4
gpt4 key购买 nike

这是链接中提出的问题的扩展:- How to insert sub-elements of xml tag at specific position using python script?

如果我使用有元素树的 python 3,它工作正常。如果我没有 python 3(因为我使用的当前版本是 2.6,无法升级),我如何使用 xml_declaration 标志写入 xml 文件?解析时似乎 xml 标志被删除。基本上,我在解析 xml 时遇到错误:-

 org.xml.sax.SAXParseException; systemId: file:config.xml; lineNumber: 1; 
columnNumber: 1; file:config.xml<Line 1, Column 1>: XML-20108: (Fatal Error) Start of root element expected.[[
at oracle.xml.parser.v2.XMLError.flushErrorHandler(XMLError.java:425)
at oracle.xml.parser.v2.XMLError.flushErrors1(XMLError.java:290)
at oracle.xml.parser.v2.NonValidatingParser.parseRootElement(NonValidatingParser.java:476)
at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:417)
at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:287)
at oracle.ossmgmt.common.util.xml.XMLUtilityParser.validate(XMLUtilityParser.java:141)
at oracle.ossmgmt.common.util.xml.XMLUtilityParser.initParse(XMLUtilityParser.java:256)
at oracle.ossmgmt.common.util.xml.XMLUtility.initParse(XMLUtility.java:381)

我也尝试过使用 lxml :-

from lxml import etree as ET
param1='conf.xml'
tree = ET.parse(param1)
print(ET.getroot())
param2='Target'
target = tree.find(param2)
#print target.tag,target.attrib
seq = 'Attribute NAME="EFG" VALUE="1234"'
param3 = seq
temp = ET.Element(param3)
temp.tail = '\n'
target.insert(4,temp)
tree.write(param1, encoding='utf-8', xml_declaration=True)

但这里我收到错误:-

Traceback (most recent call last):
File "b.py", line 10, in <module>
temp = ET.Element(param3)
File "lxml.etree.pyx", line 2346, in lxml.etree.Element
(src/lxml/lxml.etree.c:46617)
File "apihelpers.pxi", line 113, in lxml.etree._makeElement
(src/lxml/lxml.etree.c:10475)
File "apihelpers.pxi", line 1405, in lxml.etree._tagValidOrRaise
(src/lxml/lxml.etree.c:21541)
ValueError: Invalid tag name u'Attribute NAME="EFG" VALUE="1234"'

最佳答案

我不太确定你想要的最终结构是什么,但是:

seq = 'Attribute NAME="EFG" VALUE="1234"'
param3 = seq
temp = ET.Element(param3)

很可能是这样的:

seq = 'Attribute' 
#Create element <Attribute>
temp = ET.Element(seq)
#Set attributes of <Attribute>
temp.set("NAME","EFG")
temp.set("VALUE","1234")

关于python - 如何使用任何脚本(python/shell)自动插入和解析xml元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51116376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com