如何在XML中搜索带有“and”的属性文本

2024-10-01 09:15:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python和ElementTree

我有一个问题,我有两个xml文件,其中我需要将一些信息从一个复制到另一个。因此,我必须在第二个xml文件中搜索第一个xml文件中的字符串 问题是这个字符串可以包含每种字符,也可以包含“和”字符

我为搜索写了以下行:

slpRow = slpNode.find("row/[@id='%s']" % (tsSource))

在这种情况下,当tsSource包含字符的

我可以通过写作来处理这个问题

slpRow = slpNode.find('row/[@id="%s"]' % (tsSource))

在这种情况下,但这将导致在具有“角色”时出现问题

所以我的问题是,当tsSource包含“以及”

有没有办法处理这种情况

更改xml文件并使用&;#39 resp&;#34不是一个选项,因为文件是自动生成的,并且这种合并只是一个链中的一个步骤

谢谢

编辑: 说得清楚一点,这一切都是为了一个翻译工具

第一个XML文件中的XML字符串如下所示:

<tsSource>Peter said: "it is Frank's book""</tsSource>

在第二个XML中,有如下内容

<row id="Peter said: "it is Frank's book"">
   <lang id="de_DE">Peter sagte: "Es ist Frank's Buch"</lang>
</row>

问题是,我必须搜索字符串彼得说:“这是弗兰克的书”“在第二个文件中,但

slpRow = slpNode.find('row/[@id="Peter said: "it is Frank's book""]')

slpRow = slpNode.find("row/[@id='Peter said: "it is Frank's book"']")

这是失败的

错误输出如下所示:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\xml\etree\ElementPath.py", line 263, in iterfind
    selector = _cache[cache_key]
KeyError: ('row/[@id="Peter said: "it is Frank\'s book""]', None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:/Tasks/59676 Automated translation tool/TranslationMerger.py", line 63, in <module>
    slpRow = slpNode.find('row/[@id="%s"]' % (tsSource))
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\xml\etree\ElementPath.py", line 298, in find
    return next(iterfind(elem, path, namespaces), None)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\xml\etree\ElementPath.py", line 277, in iterfind
    selector.append(ops[token[0]](next, token))
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\xml\etree\ElementPath.py", line 233, in prepare_predicate
    raise SyntaxError("invalid predicate")
SyntaxError: invalid predicate

Tags: 文件frankidisitxmlfindfile