如何删除所有" \ n"使用lxml库

时间:2017-03-06 18:36:46

标签: python lxml

我试图更改xml文件中的文本值,我需要使用lxml库返回更新的xml内容。我可以成功更新该值,但更新的xml文件包含" \ n"(下一行)字符,如下所示。

输出:

<?xml version='1.0' encoding='ASCII'?>\n<Order>\n   <content>\n <sID>123</sID>\n   <spNumber>UserTemp</spNumber>\n  <client>ARRCHANA</client>\n <orderType>Dashboard</orderType>\n </content>\n
<content>\n <sID>111</sID>\n   <spNumber>UserTemp</spNumber>\n  <client>ARRCHANA</client>\n <orderType>Dashboard</orderType>\n </content>\n
</Order>

注意:我没有格式化上面的xml输出,并且发布了它是如何从输出控制台获取的。

输入:

  <Order>
    <content>
      <sID>123</sID>
       <spNumber>UserTemp</spNumber>
       <client>WALLMART</client>
       <orderType>Dashboard</orderType>
    </content>
    <content>
       <sID>111</sID>
       <spNumber>UserTemp</spNumber>
       <client>D&B</client>
       <orderType>Dashboard</orderType>
     </content>
   </Order>

另外,我尝试使用

删除输出xml文件中的\ n字符
getValue = getValue.replace('\n','') 

但是,没有运气。

以下代码用于更新xml(标记),并尝试返回更新的xml内容。

Python代码:

    from lxml import etree
    from io import StringIO
    import six
    import numpy

    def getListOfNodes(location):
        f = open(location)
        xml = f.read()
        f.close()
        #print(xml)
        getXml = etree.parse(location)
        for elm in getXml.xpath('.//Order//content/client'):
            index='ARRCHANA'
            elm.text=index
        #with open('C:\\New folder\\temp.xml','w',newline='\r\n') as writeFile:

        #writeFile.write(str(etree.tostring(getXml,pretty_print=True, xml_declaration=True)))
        getValue=str((etree.tostring(getXml,pretty_print=True, xml_declaration=True)))
        #getValue = getValue.replace('\n','') 
        #getValue=getValue.replace("\n","<br/>")
        print(getValue)
        return getValue

当我试图通过firefox浏览器打开响应有效负载时,它会显示以下错误消息:

  

XML解析错误:找不到元素位置:

     

文件:/// C:/New%20folder/Confidential.xml   第1行,第1列:

它表示&#34;没有元素在第1行,第1列和第34行找到位置;在xml文件中找到&#34; \ n&#34;其中的角色。

有人可以帮助我更好地更新文本值,并在没有任何其他字符的情况下将其返回。

1 个答案:

答案 0 :(得分:0)

使用以下脚本自行解决:

code = root.xpath('.//Order//content/client')
if code:
    code[0].text = 'ARRCHANA'
    etree.ElementTree(root).write('D:\test.xml', pretty_print=True)