简体   繁体   English

如何向没有单个根标签的现有XML添加根

[英]How to add a root to an existing XML which doesn't have a single root tag

I'm having one XML file which doesn't have a single root tag. 我有一个没有单个根标签的XML文件。 I want to add a new Root tag to this XML file. 我想向该XML文件添加一个新的Root标记。

Below is the existing XML: 以下是现有的XML:

<A>
    <Val>123</Val>
</A>

<B>
    <Val1>456</Val1>
</B>

Now I want to add a Root tag 'X', so the final XML will look like: 现在,我想添加一个根标签“ X”,因此最终的XML如下所示:

<X>
  <A>
     <Val>123</Val>
  </A>

  <B>
     <Val1>456</Val1>
  </B>
</X>

I've tried using the below python code: 我尝试使用以下python代码:

from xml.etree import ElementTree as ET  
root = ET.parse(Input_FilePath).getroot()   
newroot = ET.Element("X")    
newroot.insert(0, root)    
tree = ET.ElementTree(newroot)    
tree.write(Output_FilePath)

But at the first line I'm getting the below error: 但是在第一行,我得到以下错误:

xml.etree.ElementTree.ParseError: junk after document element: line 4, column 4

As pointed out in the comments by @kjhughes, the XML spec requires that a document must have a single root element. 正如@kjhughes的评论所指出的那样,XML规范要求文档必须具有单个根元素。

from xml.etree import ElementTree as ET

node = ET.parse(Input_FilePath)
xml.etree.ElementTree.ParseError: junk after document element: line 4, column 0

You'll need to read the file manually and add the tags yourself: 您需要手动读取文件并自己添加标签:

from xml.etree import ElementTree as ET

with open(Input_FilePath) as f:
    xml_string = '<X>' + f.read() + '</X>'

node = ET.fromstring(xml_string)

I think your can do in without xml parsers. 我认为您可以在没有xml解析器的情况下进行操作。 If your know that root tag missing, you can add it by such way. 如果您知道根标签丢失,则可以通过这种方式添加它。

with open('test.xml', 'r') as f:
    data = f.read()

with open('test.xml', 'w') as f:
    f.write("<x>\n" + data + "\n</x>")
    f.close()

If dont know, your can check it by: 如果不知道,您可以通过以下方法进行检查:

   import re
   if re.match(u"\s*<x>.*</x>", text, re.S) != None:
      #do something   
      pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM