简体   繁体   English

如何使用 Python Elementtree 修改 XML 元素

[英]How to modify XML element using Python Elementtree

I would like to modify a key value of an attribute(eg Change the value of "strokeColor" inside the "style" attribute), and the other values of this attribute can not be changed.我想修改一个属性的一个关键值(例如在“style”属性中更改“strokeColor”的值),并且该属性的其他值不能更改。 I'm using Python's ElementTree included with Python.我正在使用 Python 中包含的 Python ElementTree。

Here is an example of what I did before:这是我之前所做的一个例子:

Part of my XML example code:我的 XML 示例代码的一部分:

<?xml version="1.0"?>
<mxCell edge="1" id="line1" parent="1" source="main_wins" style="endArrow=none;html=1;entryX=0;entryY=0.25;entryDx=0;entryDy=0;strokeWidth=5;strokeColor=#32AC2D;rounded=0;edgeStyle=orthogonalEdgeStyle;exitX=1;exitY=0.5;exitDx=0;exitDy=0;" target="main-switch" value="">
</mxCell>

My python code:我的python代码:

import xml.etree.ElementTree as ET
tree = ET.parse('example.xml')
target = tree.find('.//mxCell[@id="line1"]')
target.set("strokeColor","#FF0000")
tree.write('output.xml')

My output XML:我的输出 XML:

<?xml version="1.0"?>
<mxCell edge="1" id="line1" parent="1" source="main_wins" strokeColor="#FF0000" style="endArrow=none;html=1;entryX=0;entryY=0.25;entryDx=0;entryDy=0;strokeWidth=5;strokeColor=#32AC2D;rounded=0;edgeStyle=orthogonalEdgeStyle;exitX=1;exitY=0.5;exitDx=0;exitDy=0;" target="main-switch" value="">
</mxCell>

As you can see, there is a new attribute called "strokeColor", but not changing the strokeColor value inside the "style" attribute.如您所见,有一个名为“strokeColor”的新属性,但不会更改“style”属性内的strokeColor值。 I want to change the strokeColor inside "style" attribute.我想更改“样式”属性中的strokeColor。 How can I fix this?我怎样才能解决这个问题?

Another method.另一种方法。

from simplified_scrapy import SimplifiedDoc, utils, req
html = '''
<?xml version="1.0"?>
<mxCell edge="1" id="line1" parent="1" source="main_wins" style="endArrow=none;html=1;entryX=0;entryY=0.25;entryDx=0;entryDy=0;strokeWidth=5;strokeColor=#32AC2D;rounded=0;edgeStyle=orthogonalEdgeStyle;exitX=1;exitY=0.5;exitDx=0;exitDy=0;" target="main-switch" value="">
</mxCell>
'''

doc = SimplifiedDoc(html)
mxCell = doc.select('mxCell#line1')
style = doc.replaceReg(mxCell['style'],'strokeColor=.*?;','strokeColor=#FF0000;')
mxCell.setAttr('style',style)
print(doc.html)

Result:结果:

<?xml version="1.0"?>
<mxCell edge="1" id="line1" parent="1" source="main_wins" style="endArrow=none;html=1;entryX=0;entryY=0.25;entryDx=0;entryDy=0;strokeWidth=5;strokeColor=#FF0000;rounded=0;edgeStyle=orthogonalEdgeStyle;exitX=1;exitY=0.5;exitDx=0;exitDy=0;" target="main-switch" value="">
</mxCell>

Here are more examples: https://github.com/yiyedata/simplified-scrapy-demo/tree/master/doc_examples这里有更多例子: https : //github.com/yiyedata/simplified-scrapy-demo/tree/master/doc_examples

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM