Python getting xml same childnodes in same line
<h2>I have a xml file as:</h2>

<pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;SetupConf&gt;
  &lt;LocSetup&gt;
    &lt;Src&gt;
      &lt;Dir&gt;C:\User1\test1&lt;/Dir&gt;
      &lt;Dir&gt;C:\User2\log&lt;/Dir&gt;
      &lt;Dir&gt;D:\Users\Checkup&lt;/Dir&gt;
      &lt;Dir&gt;D:\Work1&lt;/Dir&gt;
      &lt;Dir&gt;E:\job1&lt;/Dir&gt;
     &lt;/Src&gt;
  &lt;/LocSetup&gt;
  &lt;/SetupConf&gt;
</code></pre>

<hr>

<p>where <code>&lt;Dir&gt;</code> node depends on user input. In "Dir" node it may be 1,2,5,10 dir structure defined.
I am able to extract data from the xml using below Python code:</p>

<pre><code>from xml.dom import minidom

dom = minidom.parse('Test0001.xml')
Src=dom.getElementsByTagName('Src')

for node in Src:
    alist =node.getElementsByTagName('Dir')
    for a in alist:
        dirtext = a.childNodes[0].nodeValue + ','
        print dirtext
</code></pre>

<p>...............
I am getting Output in multi line as:</p>

<pre><code>C:\User1\test1,
C:\User2\log,
D:\Users\Checkup,
D:\Work1,
E:\job1,
</code></pre>

<hr>

<p>But I need the output in single line without space and remove last comma, like:</p>

<pre><code> C:\User1\test1,C:\User2\log,D:\Users\Checkup,D:\Work1,E:\job1
</code></pre>

<p>Please help me in this regard, I have tried a lot... It may be by using itertools grouping or defaultdict. Any help is greatly appreciated.</p>

<p>I presume you are trying to store the string so use <em>str.join</em>:</p>

<pre><code>output = ",".join([a.childNodes[0].nodeValue for node in Src for a in node.getElementsByTagName('Dir')])
</code></pre>

<p>You could add a trailing comma after the print so you don't get a newline printed after each<code>print dirte,</code> but that won't account for the trailing comma and does not help you if you actually want to store the string.</p>

<p>Output:</p>

<pre><code>In [1]: from xml.dom import minidom

In [2]: x = r"""&lt;?xml version="1.0" encoding="utf-8"?&gt;
   ...:   &lt;SetupConf&gt;
   ...:   &lt;LocSetup&gt;
   ...:     &lt;Src&gt;
   ...:       &lt;Dir&gt;C:\User1\test1&lt;/Dir&gt;
   ...:       &lt;Dir&gt;C:\User2\log&lt;/Dir&gt;
   ...:       &lt;Dir&gt;D:\Users\Checkup&lt;/Dir&gt;
   ...:       &lt;Dir&gt;D:\Work1&lt;/Dir&gt;
   ...:       &lt;Dir&gt;E:\job1&lt;/Dir&gt;
   ...:      &lt;/Src&gt;
   ...:   &lt;/LocSetup&gt;
   ...:   &lt;/SetupConf&gt;"""

In [3]: from StringIO import StringIO

In [4]: 

In [4]: dom = minidom.parse(StringIO(x))

In [5]: Src = dom.getElementsByTagName('Src')

In [6]: output = ",".join([a.childNodes[0].nodeValue for node in Src for a in node.getElementsByTagName('Dir')])

In [7]: print(output)
C:\User1\test1,C:\User2\log,D:\Users\Checkup,D:\Work1,E:\job1
</code></pre>

python xml