相关疑难解决方法(0)

使用python转义xml文件中的字符

我需要在一个丑陋的XML文件中转义特殊字符(5000行左右).这是我必须处理的XML的一个例子:

<root>
 <element>
  <name>name & surname</name>
  <mail>name@name.org</mail>
 </element>
</root>
Run Code Online (Sandbox Code Playgroud)

这里的问题是名称中的字符"&".你会如何使用Python库来逃避这样的特殊字符?我没有找到使用 BeautifulSoup的方法.

python xml lxml beautifulsoup special-characters

7
推荐指数
1
解决办法
1万
查看次数

标签:lxml中的名称

我正在尝试使用lxml.etree来解析Wordpress导出文档(它的XML,有点像RSS).我只对已发布的帖子感兴趣,所以我使用以下内容来浏览已发布的帖子:

for item in data.findall("item"):
    if item.find("wp:post_type").text != "post":
        continue
    if item.find("wp:status").text != "publish":
        continue
    write_post(item)
Run Code Online (Sandbox Code Playgroud)

找到data所有item标签的标签在哪里.item标签包含帖子,页面和草稿.我的问题是lxml找不到:名字中有标签的标签(例如wp:post_type).当我尝试时,item.find("wp:post_type")我收到此错误:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "lxml.etree.pyx", line 1279, in lxml.etree._Element.find (src/lxml/lxml.e
tree.c:38124)
  File "/usr/lib64/python2.7/site-packages/lxml/_elementpath.py", line 210, in f
ind
    it = iterfind(elem, path)
  File "/usr/lib64/python2.7/site-packages/lxml/_elementpath.py", line 200, in i
terfind
    selector = _build_path_iterator(path)
  File "/usr/lib64/python2.7/site-packages/lxml/_elementpath.py", line 184, in _
build_path_iterator
    selector.append(ops[token[0]](_next, token))
KeyError: ':' …
Run Code Online (Sandbox Code Playgroud)

python xml wordpress lxml elementtree

5
推荐指数
1
解决办法
3135
查看次数

用前缀的on标记解析.xml?xml.etree.ElementTree

我可以读取标签,除非有前缀。我没有运气寻找上一个问题。

我需要阅读media:content。我试过了image = node.find("media:content")。Rss输入:

<channel>
  <title>Popular  Photography in the last 1 week</title>
  <item>
    <title>foo</title>
    <media:category label="Miscellaneous">photography/misc</media:category>
    <media:content url="http://foo.com/1.jpg" height="375" width="500" medium="image"/>
  </item>
  <item> ... </item>
</channel>
Run Code Online (Sandbox Code Playgroud)

我可以阅读同级标签title

from xml.etree import ElementTree
with open('cache1.rss', 'rt') as f:
    tree = ElementTree.parse(f)

for node in tree.findall('.//channel/item'):
    title =  node.find("title").text 
Run Code Online (Sandbox Code Playgroud)

我一直在使用文档,但仍停留在“前缀”部分。

python xml xml.etree

4
推荐指数
1
解决办法
3373
查看次数