您好我有以下XML文件。我正在尝试更改ID标记中的文本文件。<ID>xxx</ID>
但无论我尝试什么,它都拒绝改变或给我回馈价值。
我是菜鸟
<ROOT xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd="w3.org/2001/XMLSchema"; xmlns:xsi="w3.org/2001/XMLSchema-instance"; xmlns="asml.com/XMLSchema/XXX/v1.0">
<ID>Some String</ID>
<AList>
<Attribute>
<Name>SomeName</Name>
<Value>SomeValue</Value>
</Attribute>
<Attribute>
<Name>SomeName_2</Name>
<Value>SomeValue_2</Value>
</Attribute>
<Attribute>
<Name>SomeName_3</Name>
<Value>SomeValue_3</Value>
</Attribute>
</AList>
<AGroupList>
<Group>
<GroupKeyList>
<Attribute>
<Name>SomeName_4</Name>
<Value>SomeValue_4</Value>
</Attribute>
</GroupKeyList>
<GroupAList>
<Attribute>
<Name>SomeName_5</Name>
<Value>SomeValue_5</Value>
</Attribute>
</GroupAList>
</Group>
<Group>
<GroupKeyList>
<Attribute>
<Name>SomeName_6</Name>
<Value>SomeValue_6</Value>
</Attribute>
</GroupKeyList>
<GroupAList>
<Attribute>
<Name>SomeName_7</Name>
<Value>SomeValue_7</Value>
</Attribute>
</GroupAList>
</Group>
</AGroupList>
from lxml import etree
xml_elem = etree.parse('path/to/file.xml')
id_elem = xml_elem.find('ID')
id_elem.text = 'xxx'
这是我的代码,我已经尝试了一切
答案 0 :(得分:0)
只需在xml的末尾添加</ROOT>
标记即可。然后它就像:
from lxml import etree
xml_elem = etree.parse('path/to/file.xml')
id_elem = xml_elem.find('ID')
id_elem.text = 'xxx'
答案 1 :(得分:0)
主要问题是未声明的命名空间前缀xmlns="asml.com/XMLSchema/XXX/v1.0"
,与其他前缀不同,没有冒号分隔的标识符。这要求您使用URI限定find
等搜索路径。请注意:这在XML文件中完全有效。
但是,您发布的标记格式不正确,因为您有一个重复的前缀:xmlns:xsd
并且在名称空间之间有分号。请注意:这不是有效的XML。如果您的实际XML <ROOT>
遵循以下格式正确的版本,则以下lxml
代码应该可以更新 ID 文本:
<强> XML 强>
<ROOT xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd2="w3.org/2001/XMLSchema"
xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns="asml.com/XMLSchema/XXX/v1.0">
...
</ROOT>
<强>的Python 强>
from lxml import etree
xml_elem = etree.parse('AGroupList.xml')
id_elem = xml_elem.find('{asml.com/XMLSchema/XXX/v1.0}ID') # URI MAPPING
id_elem.text = 'xxx'
print(etree.tostring(xml_elem, pretty_print=True).decode("UTF-8"))
<强>输出强>
<ROOT xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd2="w3.org/2001/XMLSchema" xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns="asml.com/XMLSchema/XXX/v1.0">
<ID>xxx</ID>
<AList>
<Attribute>
<Name>SomeName</Name>
<Value>SomeValue</Value>
</Attribute>
<Attribute>
<Name>SomeName_2</Name>
<Value>SomeValue_2</Value>
</Attribute>
<Attribute>
<Name>SomeName_3</Name>
<Value>SomeValue_3</Value>
</Attribute>
</AList>
<AGroupList>
<Group>
<GroupKeyList>
<Attribute>
<Name>SomeName_4</Name>
<Value>SomeValue_4</Value>
</Attribute>
</GroupKeyList>
<GroupAList>
<Attribute>
<Name>SomeName_5</Name>
<Value>SomeValue_5</Value>
</Attribute>
</GroupAList>
</Group>
<Group>
<GroupKeyList>
<Attribute>
<Name>SomeName_6</Name>
<Value>SomeValue_6</Value>
</Attribute>
</GroupKeyList>
<GroupAList>
<Attribute>
<Name>SomeName_7</Name>
<Value>SomeValue_7</Value>
</Attribute>
</GroupAList>
</Group>
</AGroupList>
</ROOT>