How to get a XML block in Python










-2















I need to rearrange / combine XML files to a new target file.



My data has the following form



<?xml version="1.0" encoding="utf-8"?>
<Level1>
<Level2>
<Level3>
<ID>1</ID>
<Name>String1</Name>
<Attribute>123</Attribute>
</Level3>
<Level3>
<ID>2</ID>
<Name>String2</Name>
<Attribute>456</Attribute>
</Level3>
<Level3>
<ID>3</ID>
<Name>String3</Name>
<Attribute>789</Attribute>
</Level3>
</Level2>
</Level1>


I'm looking for a python command to get a block of Level3 via the ID, for example



getBlock(2) should deliver



<Level3>
<ID>2</ID>
<Name>String2</Name>
<Attribute>456</Attribute>
</Level3>


Thanks in advance










share|improve this question


























    -2















    I need to rearrange / combine XML files to a new target file.



    My data has the following form



    <?xml version="1.0" encoding="utf-8"?>
    <Level1>
    <Level2>
    <Level3>
    <ID>1</ID>
    <Name>String1</Name>
    <Attribute>123</Attribute>
    </Level3>
    <Level3>
    <ID>2</ID>
    <Name>String2</Name>
    <Attribute>456</Attribute>
    </Level3>
    <Level3>
    <ID>3</ID>
    <Name>String3</Name>
    <Attribute>789</Attribute>
    </Level3>
    </Level2>
    </Level1>


    I'm looking for a python command to get a block of Level3 via the ID, for example



    getBlock(2) should deliver



    <Level3>
    <ID>2</ID>
    <Name>String2</Name>
    <Attribute>456</Attribute>
    </Level3>


    Thanks in advance










    share|improve this question
























      -2












      -2








      -2








      I need to rearrange / combine XML files to a new target file.



      My data has the following form



      <?xml version="1.0" encoding="utf-8"?>
      <Level1>
      <Level2>
      <Level3>
      <ID>1</ID>
      <Name>String1</Name>
      <Attribute>123</Attribute>
      </Level3>
      <Level3>
      <ID>2</ID>
      <Name>String2</Name>
      <Attribute>456</Attribute>
      </Level3>
      <Level3>
      <ID>3</ID>
      <Name>String3</Name>
      <Attribute>789</Attribute>
      </Level3>
      </Level2>
      </Level1>


      I'm looking for a python command to get a block of Level3 via the ID, for example



      getBlock(2) should deliver



      <Level3>
      <ID>2</ID>
      <Name>String2</Name>
      <Attribute>456</Attribute>
      </Level3>


      Thanks in advance










      share|improve this question














      I need to rearrange / combine XML files to a new target file.



      My data has the following form



      <?xml version="1.0" encoding="utf-8"?>
      <Level1>
      <Level2>
      <Level3>
      <ID>1</ID>
      <Name>String1</Name>
      <Attribute>123</Attribute>
      </Level3>
      <Level3>
      <ID>2</ID>
      <Name>String2</Name>
      <Attribute>456</Attribute>
      </Level3>
      <Level3>
      <ID>3</ID>
      <Name>String3</Name>
      <Attribute>789</Attribute>
      </Level3>
      </Level2>
      </Level1>


      I'm looking for a python command to get a block of Level3 via the ID, for example



      getBlock(2) should deliver



      <Level3>
      <ID>2</ID>
      <Name>String2</Name>
      <Attribute>456</Attribute>
      </Level3>


      Thanks in advance







      python xml






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 '18 at 22:34









      pybertpybert

      82




      82






















          3 Answers
          3






          active

          oldest

          votes


















          1














          Here's another example of using ElementTree, but without doing all of the unnecessary for loops. The testing of the ID value can be done in a simple XPath predicate.



          Example (super basic with no error checking)



          import xml.etree.ElementTree as ET

          xml = """<Level1>
          <Level2>
          <Level3>
          <ID>1</ID>
          <Name>String1</Name>
          <Attribute>123</Attribute>
          </Level3>
          <Level3>
          <ID>2</ID>
          <Name>String2</Name>
          <Attribute>456</Attribute>
          </Level3>
          <Level3>
          <ID>3</ID>
          <Name>String3</Name>
          <Attribute>789</Attribute>
          </Level3>
          </Level2>
          </Level1>"""

          tree = ET.fromstring(xml)

          def getBlock(xml_tree, id):
          return xml_tree.find(f".//Level3[ID='id']")

          print(ET.tostring(getBlock(tree, "2"), encoding="unicode"))


          this will print:



          <Level3>
          <ID>2</ID>
          <Name>String2</Name>
          <Attribute>456</Attribute>
          </Level3>


          If you'd like to use more complicated XPath, I'd recommend lxml since ElementTree's XPath support is limited.






          share|improve this answer























          • Thanks also to you - that is what I will use. I had a look at the documentation before, but could not manage it.

            – pybert
            Nov 13 '18 at 21:48


















          0














          You can use Python's XML library to do this. The following is a code snippet to show one way of obtaining an XML block based on its children's value.



          import xml.etree.ElementTree as ET

          # Parse XML file, creates ElementTree object
          tree = ET.parse("<XML_FILEPATH_HERE>")
          root = tree.getroot()

          # Get <Level3> nodes with specific id within XML ElementTree object
          def getBlock(root, id_value):
          for lvl_3 in root.findall('.//Level3'):
          if id_value == lvl_3.find('ID').text:
          print(ET.tostring(lvl_3).decode())


          You can check out the python XML library document for more information.
          https://docs.python.org/3/library/xml.etree.elementtree.html






          share|improve this answer























          • Thank you very much.

            – pybert
            Nov 13 '18 at 21:47


















          0














          The xml.etree.ElementTree package can do that for you.



          Import your data from either string or file



          Level1 = ET.fromstring(myXml) 


          And you'll have a tree in the form of a list of lists.



          Iterating, selecting or filtering over these lists becomes easy. This iterates across a list of all Level3 elements:



          Level1 = ET.fromstring(myXml)

          for Level3 in Level1.findall('.//Level3'):
          for child in Level3:
          print (child.tag, child.text)





          share|improve this answer























          • Thank you - what an elegant solution this is as well

            – pybert
            Nov 13 '18 at 21:48










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53271072%2fhow-to-get-a-xml-block-in-python%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          3 Answers
          3






          active

          oldest

          votes








          3 Answers
          3






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Here's another example of using ElementTree, but without doing all of the unnecessary for loops. The testing of the ID value can be done in a simple XPath predicate.



          Example (super basic with no error checking)



          import xml.etree.ElementTree as ET

          xml = """<Level1>
          <Level2>
          <Level3>
          <ID>1</ID>
          <Name>String1</Name>
          <Attribute>123</Attribute>
          </Level3>
          <Level3>
          <ID>2</ID>
          <Name>String2</Name>
          <Attribute>456</Attribute>
          </Level3>
          <Level3>
          <ID>3</ID>
          <Name>String3</Name>
          <Attribute>789</Attribute>
          </Level3>
          </Level2>
          </Level1>"""

          tree = ET.fromstring(xml)

          def getBlock(xml_tree, id):
          return xml_tree.find(f".//Level3[ID='id']")

          print(ET.tostring(getBlock(tree, "2"), encoding="unicode"))


          this will print:



          <Level3>
          <ID>2</ID>
          <Name>String2</Name>
          <Attribute>456</Attribute>
          </Level3>


          If you'd like to use more complicated XPath, I'd recommend lxml since ElementTree's XPath support is limited.






          share|improve this answer























          • Thanks also to you - that is what I will use. I had a look at the documentation before, but could not manage it.

            – pybert
            Nov 13 '18 at 21:48















          1














          Here's another example of using ElementTree, but without doing all of the unnecessary for loops. The testing of the ID value can be done in a simple XPath predicate.



          Example (super basic with no error checking)



          import xml.etree.ElementTree as ET

          xml = """<Level1>
          <Level2>
          <Level3>
          <ID>1</ID>
          <Name>String1</Name>
          <Attribute>123</Attribute>
          </Level3>
          <Level3>
          <ID>2</ID>
          <Name>String2</Name>
          <Attribute>456</Attribute>
          </Level3>
          <Level3>
          <ID>3</ID>
          <Name>String3</Name>
          <Attribute>789</Attribute>
          </Level3>
          </Level2>
          </Level1>"""

          tree = ET.fromstring(xml)

          def getBlock(xml_tree, id):
          return xml_tree.find(f".//Level3[ID='id']")

          print(ET.tostring(getBlock(tree, "2"), encoding="unicode"))


          this will print:



          <Level3>
          <ID>2</ID>
          <Name>String2</Name>
          <Attribute>456</Attribute>
          </Level3>


          If you'd like to use more complicated XPath, I'd recommend lxml since ElementTree's XPath support is limited.






          share|improve this answer























          • Thanks also to you - that is what I will use. I had a look at the documentation before, but could not manage it.

            – pybert
            Nov 13 '18 at 21:48













          1












          1








          1







          Here's another example of using ElementTree, but without doing all of the unnecessary for loops. The testing of the ID value can be done in a simple XPath predicate.



          Example (super basic with no error checking)



          import xml.etree.ElementTree as ET

          xml = """<Level1>
          <Level2>
          <Level3>
          <ID>1</ID>
          <Name>String1</Name>
          <Attribute>123</Attribute>
          </Level3>
          <Level3>
          <ID>2</ID>
          <Name>String2</Name>
          <Attribute>456</Attribute>
          </Level3>
          <Level3>
          <ID>3</ID>
          <Name>String3</Name>
          <Attribute>789</Attribute>
          </Level3>
          </Level2>
          </Level1>"""

          tree = ET.fromstring(xml)

          def getBlock(xml_tree, id):
          return xml_tree.find(f".//Level3[ID='id']")

          print(ET.tostring(getBlock(tree, "2"), encoding="unicode"))


          this will print:



          <Level3>
          <ID>2</ID>
          <Name>String2</Name>
          <Attribute>456</Attribute>
          </Level3>


          If you'd like to use more complicated XPath, I'd recommend lxml since ElementTree's XPath support is limited.






          share|improve this answer













          Here's another example of using ElementTree, but without doing all of the unnecessary for loops. The testing of the ID value can be done in a simple XPath predicate.



          Example (super basic with no error checking)



          import xml.etree.ElementTree as ET

          xml = """<Level1>
          <Level2>
          <Level3>
          <ID>1</ID>
          <Name>String1</Name>
          <Attribute>123</Attribute>
          </Level3>
          <Level3>
          <ID>2</ID>
          <Name>String2</Name>
          <Attribute>456</Attribute>
          </Level3>
          <Level3>
          <ID>3</ID>
          <Name>String3</Name>
          <Attribute>789</Attribute>
          </Level3>
          </Level2>
          </Level1>"""

          tree = ET.fromstring(xml)

          def getBlock(xml_tree, id):
          return xml_tree.find(f".//Level3[ID='id']")

          print(ET.tostring(getBlock(tree, "2"), encoding="unicode"))


          this will print:



          <Level3>
          <ID>2</ID>
          <Name>String2</Name>
          <Attribute>456</Attribute>
          </Level3>


          If you'd like to use more complicated XPath, I'd recommend lxml since ElementTree's XPath support is limited.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 12 '18 at 23:56









          Daniel HaleyDaniel Haley

          38.7k45380




          38.7k45380












          • Thanks also to you - that is what I will use. I had a look at the documentation before, but could not manage it.

            – pybert
            Nov 13 '18 at 21:48

















          • Thanks also to you - that is what I will use. I had a look at the documentation before, but could not manage it.

            – pybert
            Nov 13 '18 at 21:48
















          Thanks also to you - that is what I will use. I had a look at the documentation before, but could not manage it.

          – pybert
          Nov 13 '18 at 21:48





          Thanks also to you - that is what I will use. I had a look at the documentation before, but could not manage it.

          – pybert
          Nov 13 '18 at 21:48













          0














          You can use Python's XML library to do this. The following is a code snippet to show one way of obtaining an XML block based on its children's value.



          import xml.etree.ElementTree as ET

          # Parse XML file, creates ElementTree object
          tree = ET.parse("<XML_FILEPATH_HERE>")
          root = tree.getroot()

          # Get <Level3> nodes with specific id within XML ElementTree object
          def getBlock(root, id_value):
          for lvl_3 in root.findall('.//Level3'):
          if id_value == lvl_3.find('ID').text:
          print(ET.tostring(lvl_3).decode())


          You can check out the python XML library document for more information.
          https://docs.python.org/3/library/xml.etree.elementtree.html






          share|improve this answer























          • Thank you very much.

            – pybert
            Nov 13 '18 at 21:47















          0














          You can use Python's XML library to do this. The following is a code snippet to show one way of obtaining an XML block based on its children's value.



          import xml.etree.ElementTree as ET

          # Parse XML file, creates ElementTree object
          tree = ET.parse("<XML_FILEPATH_HERE>")
          root = tree.getroot()

          # Get <Level3> nodes with specific id within XML ElementTree object
          def getBlock(root, id_value):
          for lvl_3 in root.findall('.//Level3'):
          if id_value == lvl_3.find('ID').text:
          print(ET.tostring(lvl_3).decode())


          You can check out the python XML library document for more information.
          https://docs.python.org/3/library/xml.etree.elementtree.html






          share|improve this answer























          • Thank you very much.

            – pybert
            Nov 13 '18 at 21:47













          0












          0








          0







          You can use Python's XML library to do this. The following is a code snippet to show one way of obtaining an XML block based on its children's value.



          import xml.etree.ElementTree as ET

          # Parse XML file, creates ElementTree object
          tree = ET.parse("<XML_FILEPATH_HERE>")
          root = tree.getroot()

          # Get <Level3> nodes with specific id within XML ElementTree object
          def getBlock(root, id_value):
          for lvl_3 in root.findall('.//Level3'):
          if id_value == lvl_3.find('ID').text:
          print(ET.tostring(lvl_3).decode())


          You can check out the python XML library document for more information.
          https://docs.python.org/3/library/xml.etree.elementtree.html






          share|improve this answer













          You can use Python's XML library to do this. The following is a code snippet to show one way of obtaining an XML block based on its children's value.



          import xml.etree.ElementTree as ET

          # Parse XML file, creates ElementTree object
          tree = ET.parse("<XML_FILEPATH_HERE>")
          root = tree.getroot()

          # Get <Level3> nodes with specific id within XML ElementTree object
          def getBlock(root, id_value):
          for lvl_3 in root.findall('.//Level3'):
          if id_value == lvl_3.find('ID').text:
          print(ET.tostring(lvl_3).decode())


          You can check out the python XML library document for more information.
          https://docs.python.org/3/library/xml.etree.elementtree.html







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 12 '18 at 23:32









          boonwjboonwj

          2169




          2169












          • Thank you very much.

            – pybert
            Nov 13 '18 at 21:47

















          • Thank you very much.

            – pybert
            Nov 13 '18 at 21:47
















          Thank you very much.

          – pybert
          Nov 13 '18 at 21:47





          Thank you very much.

          – pybert
          Nov 13 '18 at 21:47











          0














          The xml.etree.ElementTree package can do that for you.



          Import your data from either string or file



          Level1 = ET.fromstring(myXml) 


          And you'll have a tree in the form of a list of lists.



          Iterating, selecting or filtering over these lists becomes easy. This iterates across a list of all Level3 elements:



          Level1 = ET.fromstring(myXml)

          for Level3 in Level1.findall('.//Level3'):
          for child in Level3:
          print (child.tag, child.text)





          share|improve this answer























          • Thank you - what an elegant solution this is as well

            – pybert
            Nov 13 '18 at 21:48















          0














          The xml.etree.ElementTree package can do that for you.



          Import your data from either string or file



          Level1 = ET.fromstring(myXml) 


          And you'll have a tree in the form of a list of lists.



          Iterating, selecting or filtering over these lists becomes easy. This iterates across a list of all Level3 elements:



          Level1 = ET.fromstring(myXml)

          for Level3 in Level1.findall('.//Level3'):
          for child in Level3:
          print (child.tag, child.text)





          share|improve this answer























          • Thank you - what an elegant solution this is as well

            – pybert
            Nov 13 '18 at 21:48













          0












          0








          0







          The xml.etree.ElementTree package can do that for you.



          Import your data from either string or file



          Level1 = ET.fromstring(myXml) 


          And you'll have a tree in the form of a list of lists.



          Iterating, selecting or filtering over these lists becomes easy. This iterates across a list of all Level3 elements:



          Level1 = ET.fromstring(myXml)

          for Level3 in Level1.findall('.//Level3'):
          for child in Level3:
          print (child.tag, child.text)





          share|improve this answer













          The xml.etree.ElementTree package can do that for you.



          Import your data from either string or file



          Level1 = ET.fromstring(myXml) 


          And you'll have a tree in the form of a list of lists.



          Iterating, selecting or filtering over these lists becomes easy. This iterates across a list of all Level3 elements:



          Level1 = ET.fromstring(myXml)

          for Level3 in Level1.findall('.//Level3'):
          for child in Level3:
          print (child.tag, child.text)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 12 '18 at 23:35









          weegoloweegolo

          394




          394












          • Thank you - what an elegant solution this is as well

            – pybert
            Nov 13 '18 at 21:48

















          • Thank you - what an elegant solution this is as well

            – pybert
            Nov 13 '18 at 21:48
















          Thank you - what an elegant solution this is as well

          – pybert
          Nov 13 '18 at 21:48





          Thank you - what an elegant solution this is as well

          – pybert
          Nov 13 '18 at 21:48

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53271072%2fhow-to-get-a-xml-block-in-python%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Use pre created SQLite database for Android project in kotlin

          Darth Vader #20

          Ondo