Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:XMLElementTree(或lxml)中的名称空间_Python_Xml_Namespaces_Elementtree - Fatal编程技术网

Python:XMLElementTree(或lxml)中的名称空间

Python:XMLElementTree(或lxml)中的名称空间,python,xml,namespaces,elementtree,Python,Xml,Namespaces,Elementtree,我想检索一个遗留xml文件,操作并保存它 这是我的密码: from xml.etree import cElementTree as ET NS = "{http://www.somedomain.com/XI/Traffic/10}" def fix_xml(filename): f = ET.parse(filename) root = f.getroot() eventlist = root.findall("%(ns)Event" % {'ns':NS })

我想检索一个遗留xml文件,操作并保存它

这是我的密码:

from xml.etree import cElementTree as ET
NS = "{http://www.somedomain.com/XI/Traffic/10}"

def fix_xml(filename):
    f = ET.parse(filename)
    root = f.getroot()
    eventlist = root.findall("%(ns)Event" % {'ns':NS })
    xpath = "%(ns)sEventDetail/%(ns)sEventDescription" % {'ns':NS }
    for event in eventlist:
        desc = event.find(xpath)
        desc.text = desc.text.upper() # do some editting to the text.

    ET.ElementTree(root, nsmap=NS).write("out.xml", encoding="utf-8")


shorten_xml("test.xml")
我加载的文件包含:

xmlns="http://www.somedomain.com/XI/Traffic/10"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.somedomain.com/XI/Traffic/10 10.xds"
在根标记处

我有以下与命名空间相关的问题:

  • 如您所见,对于每个标记调用,我都在开始时提供名称空间以检索子级
  • 生成的xml文件在开始时没有
  • 输出处的标记包含这样的
    ,而我需要输出为原始的
    ,开头没有名称空间
如何解决这些问题?

请看下面的示例。还有这个

问题1:像其他人一样忍受它。尝试
ns+“事件”
而不是
“%(ns)事件”%{'ns':ns}

问题2:默认情况下,只有在需要时才编写XML声明。您可以在
write()
调用中使用
xml\u declaration=True
强制执行它(仅限lxml)


问题3:
nsmap
arg似乎仅为lxml。AFAICT它需要一个映射,而不是一个字符串。请尝试
nsmap={None:NS}
。effbot文章中有一节介绍了解决此问题的方法。

按顺序回答您的问题:

  • 您不能忽略名称空间,不能忽略
    .findall()
    使用的路径语法,也不能忽略“real”xpath(由lxml支持)中的名称空间:在这里,您仍然必须使用前缀,并且仍然需要提供一些前缀到uri的映射

  • 使用
    xml\u declaration=True
    以及
    encoding='utf-8'
    .write()
    调用(在lxml中可用,但在stdlib xml.etree中,我相信只有在python 2.7之后才有)

  • 我相信lxml会按照您的意愿行事