【问题标题】:Using lxml, how can I append to a document and then wrap the entire document in a tag so I can search it with xpath?使用 lxml,我如何附加到文档,然后将整个文档包装在标签中,以便我可以使用 xpath 搜索它?
【发布时间】:2014-07-08 02:50:57
【问题描述】:

如果没有将整个文档包装在单个标签中,xpath 会给我“文档末尾的额外内容”错误。这没问题,我可以将整个东西包装在一个标签中。但是,在我的程序中,您将多次写入该文档,然后进入该文档然后对其进行编辑,这违背了拥有该程序的目的。

这是我写入文档的代码:

def write():
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

        post = open('post.txt', 'w')
        document = etree.Element('document')
        title = raw_input('title>>')

        while 1:
            message = raw_input('post>>')
            post.write(message + '\n')
            if '[done]' in message:
                tags = raw_input('tags>>')
                break



        post = open('post.txt', 'r')
        postf = post.read()

        article = etree.SubElement(document, 'article', title=title, date=st, tags=tags)
        article.text = postf

        post.close()

        with open('postf.txt', 'a') as file:
            file.write(etree.tostring(article, pretty_print=True) + '\n')
            file.close()

        return document, article

这是搜索文档的代码:

if search in command:
    query = command.replace(search + ' ', "") #remove precursor
    post = open('postf.txt', 'r')
    postf = str(post.read())

    root = etree.fromstring(postf)

    articles = root.xpath('//article[contains(@tags, "%s")]' % query)

    for article in articles:
        print etree.tostring(article, pretty_print=True)

在调用每个“write()”函数后,我可以在某处添加一个步骤,将整个文档包装在一个标记中吗?

如果需要发布我的完整程序,请告诉我,但我相当确定这是代码中唯一会影响我想要做的事情的部分。如果没有,请发表评论,我将编辑其余部分。谢谢。

【问题讨论】:

    标签: python-2.7 xpath xml-parsing lxml


    【解决方案1】:

    您可以通过将以下文件放在与该文件相同的目录中,围绕“多根”XML 文件创建一个“虚拟包装器”:

    <!DOCTYPE doc [
    <!ENTITY e SYSTEM "article.xml">
    ]>
    <doc>&e;</doc>
    

    然后,您可以在此虚拟文档中定位 XPath 表达式。这样您就可以保留将数据附加到真实 article.xml 的能力,同时能够随时执行 XPath 查询。

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 2011-11-20
      相关资源
      最近更新 更多