【问题标题】:How to extract the string values "Hello" and "World" from the XML using Python 2.6如何使用 Python 2.6 从 XML 中提取字符串值“Hello”和“World”
【发布时间】:2014-06-03 00:40:54
【问题描述】:

我需要使用 Python 2.6 提取字符串“Hello”和“World”。请指教。

<Translate_Array_Request>
  <App_Id />
  <From>language-code</From>
  <Options>
    <Category xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" >string-value</Category>
    <Content Type xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2">text/plain</ContentType>
    <Reserved Flags xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" />
    <State xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" >int-value</State>
    <Uri xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" >string-value</Uri>
    <User xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" >string-value</User>
  </Options>
  <Texts>
    <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">**Hello**</string>
    <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">**World**</string>
    </Texts>
  <To>language-code</To>
</Translate_Array_Request>

【问题讨论】:

  • 如果有的话,你尝试过什么?

标签: python python-2.6


【解决方案1】:

python 中有多个库可以让您从 XML 中解析和提取数据。一种方法是使用ElementTree XML python API。假设输入保存为字符串xml_data,这就是你要做的:

>>> import xml.etree.ElementTree as ET
>>> root = ET.fromstring(xml_data)
>>> texts = root.find('Texts')
>>> for data in texts:
...     print data.text
...
**Hello**
**World**

【讨论】:

    【解决方案2】:

    使用 xml 包,执行以下操作:

    将 xml.etree.ElementTree 导入为 ET

    def getTags( xml )
      root = ET.fromstring( xml )
      res = []
    
      for tag in root.iter("string"):
        res.append(tag.text)
    
      return res
    

    【讨论】:

      【解决方案3】:

      使用 minidom 的替代解决方案,

      import xml.dom.minidom as minidom
      def getTags(xml)
        root = minidom.parseString(xml)
        return [i.firstChild.nodeValue for i in root.getElementsByTagName('string')]
      

      【讨论】:

      • 出于测试目的,我将 XMLRequest 保存在 temp.xml 文件中。上面代码中的文件名应该在哪里指定?
      猜你喜欢
      • 2011-12-14
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 2016-04-05
      • 2012-05-10
      • 2012-04-03
      相关资源
      最近更新 更多