Python创建<?xml version="1.0" encoding="UTF-8"?>的xml文件
时间: 2023-06-03 13:04:44 浏览: 598
可以使用Python中的xml库来创建xml文件,并设置文件头为 <?xml version="1.0" encoding="UTF-8"?>。具体实现方式可以参考以下代码:
```python
import xml.etree.ElementTree as ET
root = ET.Element("root")
child1 = ET.SubElement(root, "child1")
child1.text = "This is child1"
child2 = ET.SubElement(root, "child2")
child2.text = "This is child2"
tree = ET.ElementTree(root)
# 设置xml文件头
xml_declaration = '<?xml version="1.0" encoding="UTF-8"?>'
tree.write("example.xml", xml_declaration=xml_declaration, encoding="UTF-8")
```
执行以上代码后,会在当前目录下生成名为 example.xml 的文件,其内容为:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child1>This is child1</child1>
<child2>This is child2</child2>
</root>
```
相关问题
Python添加<?xml version="1.0" encoding="UTF-8"?>
您可以使用以下代码来在 Python 中添加 <?xml version="1.0" encoding="UTF-8"?>:
```python
with open('file.xml', 'w', encoding='utf-8') as f:
f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
# write other XML content below
```
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="JavaScriptSettings"> <option name="languageLevel" value="ES6" /> </component> </project>将这段代码解析为.py文件
这段代码是一个XML文件,不是Python代码。如果你需要将这段XML代码解析为Python代码,可以使用Python内置的xml库来解析。下面是一个示例代码:
```python
import xml.etree.ElementTree as ET
xml_code = '<?xml version="1.0" encoding="UTF-8"?><project version="4"><component name="JavaScriptSettings"><option name="languageLevel" value="ES6" /></component></project>'
root = ET.fromstring(xml_code)
for component in root.findall('component'):
if component.get('name') == 'JavaScriptSettings':
for option in component.findall('option'):
if option.get('name') == 'languageLevel':
print('JavaScript语言级别为:', option.get('value'))
```
这段代码将会输出:JavaScript语言级别为:ES6
阅读全文