Python Forum

Full Version: Add root node to xml
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I generated xml string and want to add root node:

#lets create a dataframe
df=pd.DataFrame({'A':[1,2,3],'B':['a','b','c']})

def to_xml(df):
    def row_xml(row):
        xml = ['<item>']
        for i, col_name in enumerate(row.index):
            xml.append('  <{0}>{1}</{0}>'.format(col_name, row.iloc[i]))
        xml.append('</item>')
        return '\n'.join(xml)
    res = '\n'.join(df.apply(row_xml, axis=1))
    return(res)
1
to_xml(df)
<item>
<A>1</A>
<B>a</B
</item>
<item>
<A>2</A>
<B>b</B>
</item>
<item>
<A>3</A>
<B>c</B>
</item>
...
========================
Add root node:


<Header>
     <Name></Names>
     <Release><</software>
<Header>

<Values>
    <item>
       <A>1</A>
       <B>a</B
   </item>
   <item>
       <A>2</A>
       <B>b</B>
   </item>
   <item>
       <A>3</A>
       <B>c</B>
   </item>
<Values>
Do you have a question? Why are you manipulating a string, instead of using objects to create the XML (e.g. with xml.etree.ElementTree)?
(Oct-15-2022, 02:26 PM)ndc85430 Wrote: [ -> ]Do you have a question? Why are you manipulating a string, instead of using objects to create the XML (e.g. with xml.etree.ElementTree)?
I Have data frame, but now my code only output


<item>
<A>1</A>
<B>a</B
</item>
<item>
<A>2</A>
<B>b</B>
</item>
<item>
<A>3</A>
<B>c</B>
</item>

But I want to add header and root node so the my output looks like:

<Header>
     <Name></Names>
     <Release><</software>
<Header>

<Values>
<item>
    <A>1</A>
    <B>a</B
</item>
<item>
    <A>2</A>
    <B>b</B>
</item>
<item>
    <A>3</A>
    <B>c</B>
</item>
<Values>
(Oct-15-2022, 02:29 PM)SriRajesh Wrote: [ -> ]But I want to add header and root node so the my output looks like:
You use library that deal with this as ndc85430 posted,i always use BS | lxml for task like this like.
Example.
from bs4 import BeautifulSoup

xml = '''\
<values>
    <item>
       <A>1</A>
       <B>a</B
   </item>
   <item>
       <A>2</A>
       <B>b</B>
   </item>
   <item>
       <A>3</A>
       <B>c</B>
   </item>
</values>'''

soup = BeautifulSoup(xml, "xml")
# Make headertag
new_tag = soup.new_tag("header")
soup.select_one('values').insert_before(new_tag)

# Append sub tag to header tag
header_tag = soup.select_one('header')
new_tag1 = soup.new_tag("names")
new_tag1.string = "test"
header_tag.append(new_tag1)
print(soup)
Output:
<?xml version="1.0" encoding="utf-8"?> <header> <names>test</names> </header> <values> <item> <A>1</A> <B>a</B> </item> <item> <A>2</A> <B>b</B> </item> <item> <A>3</A> <B>c</B> </item> </values>