我在这个主题上做了很多研究,我遇到的问题取决于我使用的方法。使用的文件是XML文件。我想要做的是使用一个模板文件EX:
<?xml version= "1.0" encoding= "iso-8859-1"?>
<r:root xmlns:p="./file" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Version>1</Version>
<Parent Number="">
</Parent>
</r:root>
并在父标签下将另一个文件中的节点插入到模板中。插入文件:
<?xml version= "1.0" encoding= "iso-8859-1"?>
<Child ID="" Type="">
<Sub1>text</Sub1>
<Sub2>text</Sub2>
<Sub3>text</Sub3>
<Sub4>text</Sub4>
<Nest1>
<Sub1>text</Sub1>
<Sub2>text</Sub2>
</Nest1>
</Child>
我目前正在尝试使用深度复制方法,在该方法中我正在解析文件并深入复制根目录。
lxml方法问题:当我将节点插入父树并尝试打印出新树时,这就是输出。
<?xml version= "1.0" encoding= "iso-8859-1"?>
<r:root xmlns:p="./file" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Version>1</Version>
<Parent Number="">
<Child ID="" Type=""><Sub1>text</Sub1><Sub2>text</Sub2><Sub3>text</Sub3><Sub4>text</Sub4><Nest1><Sub1>text</Sub1><Sub2>text</Sub2></Nest1></Child></Parent>
</r:root>
elementtree方法问题:我无法使用minidom prettify获得正确的打印效果,并将r:root转换为ns0:root。
import xml.etree.ElementTree as ET
import xml.dom.minidom as MD
def prettify(root, encoder):
rough_string = ET.tostring(root, str(encoder))
reparse = MD.parseString(rough_string)
return reparse.topprettyxml(indent=" ", newl="")
美丽的汤方法问题:当它用HTML解析时,我让它工作了,但是所有的东西都是小写的,我不能这样做,我不能让xml解析器工作。
我所需要的是,当我插入节点时,它保持了漂亮的结构。
为了让它工作,我在这里做错了什么或错过了什么?
发布于 2021-07-20 01:27:18
由于您的问题被标记为lxml
,因此让我们使用它。但首先请注意,在模板文件中有一个拼写错误:xmlns:p="./file"
可能应该是xmlns:r="./file"
(因为您的第一个元素是r:root
)。假设这个问题已经解决,你可以:
from lxml import etree
temp = """<?xml version= "1.0" encoding= "iso-8859-1"?>
<r:root xmlns:r="./file" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Version>1</Version>
<Parent Number="">
</Parent>
</r:root>"""
#I modified the source file a bit to differentiate the various element levels
source = """<?xml version= "1.0" encoding= "iso-8859-1"?>
<Child ID="" Type="">
<Sub1>text1</Sub1>
<Sub2>text2</Sub2>
<Sub3>text3</Sub3>
<Sub4>text4</Sub4>
<Nest1>
<NSub1>textN1</NSub1>
<NSub2>textN2</NSub2>
</Nest1>
</Child>"""
temp_doc = etree.XML(temp.encode())
source_doc = etree.XML(source.encode())
#get the elements to be inserted in the template
ins = source_doc.xpath('//Child/*')
#locate the place in the template where these elements are to be inserted
destination = temp_doc.xpath('//Parent')[0]
#now insert them
for i in reversed(ins):
destination.insert(0,i)
print(etree.tostring(temp_doc).decode())
输出:
<r:root xmlns:r="./file" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Version>1</Version>
<Parent Number="">
<Sub1>text1</Sub1>
<Sub2>text2</Sub2>
<Sub3>text3</Sub3>
<Sub4>text4</Sub4>
<Nest1>
<NSub1>textN1</NSub1>
<NSub2>textN2</NSub2>
</Nest1>
</Parent>
</r:root>
https://stackoverflow.com/questions/68446063
复制