continuing xml parsing if tag not found in python using minidom












0

















Sample XML Document



<Authors>
<Author>
<LastName>def</LastName>
<age>20</age>
</Author>
<Author>
<ForeName>ghi</ForeName>
<age>22</age>
</Author>
<Author>
<ForeName>mno</ForeName>
<LastName>pqr</LastName>
<age>23</age>
</Author>
</Authors>




Sample output



Author:
FirstName : -
LastName : def

Author:
FirstName : ghi
LastName : -

Author:
FirstName : mno
LastName : pqr




Sample Code



import xml.dom.minidom
# use the parse() function to load and parse an XML file
doc = xml.dom.minidom.parse("sampleinput.xml");
auth = doc.getElementsByTagName('Author')
for a in auth:
print("Author:")
try:
print("FirstName : ",a.getElementsByTagName("ForeName")[0].firstChild.data)
except:
print("FirstName : - ")
try:
print("LastName : ",a.getElementsByTagName("LastName")[0].firstChild.data)
except:
print("LastName : - ")


i want to insert an '-' symbol if corresponding tag is not found. is there any other reliable way to do that rather than try and except?










share|improve this question



























    0

















    Sample XML Document



    <Authors>
    <Author>
    <LastName>def</LastName>
    <age>20</age>
    </Author>
    <Author>
    <ForeName>ghi</ForeName>
    <age>22</age>
    </Author>
    <Author>
    <ForeName>mno</ForeName>
    <LastName>pqr</LastName>
    <age>23</age>
    </Author>
    </Authors>




    Sample output



    Author:
    FirstName : -
    LastName : def

    Author:
    FirstName : ghi
    LastName : -

    Author:
    FirstName : mno
    LastName : pqr




    Sample Code



    import xml.dom.minidom
    # use the parse() function to load and parse an XML file
    doc = xml.dom.minidom.parse("sampleinput.xml");
    auth = doc.getElementsByTagName('Author')
    for a in auth:
    print("Author:")
    try:
    print("FirstName : ",a.getElementsByTagName("ForeName")[0].firstChild.data)
    except:
    print("FirstName : - ")
    try:
    print("LastName : ",a.getElementsByTagName("LastName")[0].firstChild.data)
    except:
    print("LastName : - ")


    i want to insert an '-' symbol if corresponding tag is not found. is there any other reliable way to do that rather than try and except?










    share|improve this question

























      0












      0








      0










      Sample XML Document



      <Authors>
      <Author>
      <LastName>def</LastName>
      <age>20</age>
      </Author>
      <Author>
      <ForeName>ghi</ForeName>
      <age>22</age>
      </Author>
      <Author>
      <ForeName>mno</ForeName>
      <LastName>pqr</LastName>
      <age>23</age>
      </Author>
      </Authors>




      Sample output



      Author:
      FirstName : -
      LastName : def

      Author:
      FirstName : ghi
      LastName : -

      Author:
      FirstName : mno
      LastName : pqr




      Sample Code



      import xml.dom.minidom
      # use the parse() function to load and parse an XML file
      doc = xml.dom.minidom.parse("sampleinput.xml");
      auth = doc.getElementsByTagName('Author')
      for a in auth:
      print("Author:")
      try:
      print("FirstName : ",a.getElementsByTagName("ForeName")[0].firstChild.data)
      except:
      print("FirstName : - ")
      try:
      print("LastName : ",a.getElementsByTagName("LastName")[0].firstChild.data)
      except:
      print("LastName : - ")


      i want to insert an '-' symbol if corresponding tag is not found. is there any other reliable way to do that rather than try and except?










      share|improve this question
















      Sample XML Document



      <Authors>
      <Author>
      <LastName>def</LastName>
      <age>20</age>
      </Author>
      <Author>
      <ForeName>ghi</ForeName>
      <age>22</age>
      </Author>
      <Author>
      <ForeName>mno</ForeName>
      <LastName>pqr</LastName>
      <age>23</age>
      </Author>
      </Authors>




      Sample output



      Author:
      FirstName : -
      LastName : def

      Author:
      FirstName : ghi
      LastName : -

      Author:
      FirstName : mno
      LastName : pqr




      Sample Code



      import xml.dom.minidom
      # use the parse() function to load and parse an XML file
      doc = xml.dom.minidom.parse("sampleinput.xml");
      auth = doc.getElementsByTagName('Author')
      for a in auth:
      print("Author:")
      try:
      print("FirstName : ",a.getElementsByTagName("ForeName")[0].firstChild.data)
      except:
      print("FirstName : - ")
      try:
      print("LastName : ",a.getElementsByTagName("LastName")[0].firstChild.data)
      except:
      print("LastName : - ")


      i want to insert an '-' symbol if corresponding tag is not found. is there any other reliable way to do that rather than try and except?







      python






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '18 at 5:04









      vinay nischalvinay nischal

      65




      65
























          1 Answer
          1






          active

          oldest

          votes


















          0














          There is! So lets see what happens when you actually run a.getElementsByTagName if it does not contain your target element.



          for a in auth:
          print(a.getElementsByTagName("ForeName"))

          >>

          [<DOM Element: ForeName at 0x163a17226d0>]
          [<DOM Element: ForeName at 0x163a1722898>]


          Right, now we know that if you try to get an element it does not have, it returns an empty list and is also aligned to the documentation:




          A NodeList represents a sequence of nodes. These objects are used in
          two ways in the DOM Core recommendation: an Element object provides
          one as its list of child nodes, and the getElementsByTagName() and
          getElementsByTagNameNS() methods of Node return objects with this
          interface to represent query results.




          Now instead of doing the try and except loop, you can explicitly check if the element is present before printing your data with:



          for a in auth:
          if a.getElementsByTagName("ForeName"):
          print("FirstName : ",a.getElementsByTagName("ForeName")[0].firstChild.data)
          else:
          print("FirstName : - ")

          >>
          FirstName : -
          FirstName : ghi
          FirstName : mno


          Here the if block checks to see if it is not empty and followed by a print. Ff the NodeList is empty, it prints the dash.






          share|improve this answer























            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%2f53424190%2fcontinuing-xml-parsing-if-tag-not-found-in-python-using-minidom%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            There is! So lets see what happens when you actually run a.getElementsByTagName if it does not contain your target element.



            for a in auth:
            print(a.getElementsByTagName("ForeName"))

            >>

            [<DOM Element: ForeName at 0x163a17226d0>]
            [<DOM Element: ForeName at 0x163a1722898>]


            Right, now we know that if you try to get an element it does not have, it returns an empty list and is also aligned to the documentation:




            A NodeList represents a sequence of nodes. These objects are used in
            two ways in the DOM Core recommendation: an Element object provides
            one as its list of child nodes, and the getElementsByTagName() and
            getElementsByTagNameNS() methods of Node return objects with this
            interface to represent query results.




            Now instead of doing the try and except loop, you can explicitly check if the element is present before printing your data with:



            for a in auth:
            if a.getElementsByTagName("ForeName"):
            print("FirstName : ",a.getElementsByTagName("ForeName")[0].firstChild.data)
            else:
            print("FirstName : - ")

            >>
            FirstName : -
            FirstName : ghi
            FirstName : mno


            Here the if block checks to see if it is not empty and followed by a print. Ff the NodeList is empty, it prints the dash.






            share|improve this answer




























              0














              There is! So lets see what happens when you actually run a.getElementsByTagName if it does not contain your target element.



              for a in auth:
              print(a.getElementsByTagName("ForeName"))

              >>

              [<DOM Element: ForeName at 0x163a17226d0>]
              [<DOM Element: ForeName at 0x163a1722898>]


              Right, now we know that if you try to get an element it does not have, it returns an empty list and is also aligned to the documentation:




              A NodeList represents a sequence of nodes. These objects are used in
              two ways in the DOM Core recommendation: an Element object provides
              one as its list of child nodes, and the getElementsByTagName() and
              getElementsByTagNameNS() methods of Node return objects with this
              interface to represent query results.




              Now instead of doing the try and except loop, you can explicitly check if the element is present before printing your data with:



              for a in auth:
              if a.getElementsByTagName("ForeName"):
              print("FirstName : ",a.getElementsByTagName("ForeName")[0].firstChild.data)
              else:
              print("FirstName : - ")

              >>
              FirstName : -
              FirstName : ghi
              FirstName : mno


              Here the if block checks to see if it is not empty and followed by a print. Ff the NodeList is empty, it prints the dash.






              share|improve this answer


























                0












                0








                0







                There is! So lets see what happens when you actually run a.getElementsByTagName if it does not contain your target element.



                for a in auth:
                print(a.getElementsByTagName("ForeName"))

                >>

                [<DOM Element: ForeName at 0x163a17226d0>]
                [<DOM Element: ForeName at 0x163a1722898>]


                Right, now we know that if you try to get an element it does not have, it returns an empty list and is also aligned to the documentation:




                A NodeList represents a sequence of nodes. These objects are used in
                two ways in the DOM Core recommendation: an Element object provides
                one as its list of child nodes, and the getElementsByTagName() and
                getElementsByTagNameNS() methods of Node return objects with this
                interface to represent query results.




                Now instead of doing the try and except loop, you can explicitly check if the element is present before printing your data with:



                for a in auth:
                if a.getElementsByTagName("ForeName"):
                print("FirstName : ",a.getElementsByTagName("ForeName")[0].firstChild.data)
                else:
                print("FirstName : - ")

                >>
                FirstName : -
                FirstName : ghi
                FirstName : mno


                Here the if block checks to see if it is not empty and followed by a print. Ff the NodeList is empty, it prints the dash.






                share|improve this answer













                There is! So lets see what happens when you actually run a.getElementsByTagName if it does not contain your target element.



                for a in auth:
                print(a.getElementsByTagName("ForeName"))

                >>

                [<DOM Element: ForeName at 0x163a17226d0>]
                [<DOM Element: ForeName at 0x163a1722898>]


                Right, now we know that if you try to get an element it does not have, it returns an empty list and is also aligned to the documentation:




                A NodeList represents a sequence of nodes. These objects are used in
                two ways in the DOM Core recommendation: an Element object provides
                one as its list of child nodes, and the getElementsByTagName() and
                getElementsByTagNameNS() methods of Node return objects with this
                interface to represent query results.




                Now instead of doing the try and except loop, you can explicitly check if the element is present before printing your data with:



                for a in auth:
                if a.getElementsByTagName("ForeName"):
                print("FirstName : ",a.getElementsByTagName("ForeName")[0].firstChild.data)
                else:
                print("FirstName : - ")

                >>
                FirstName : -
                FirstName : ghi
                FirstName : mno


                Here the if block checks to see if it is not empty and followed by a print. Ff the NodeList is empty, it prints the dash.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 22 '18 at 5:53









                BernardLBernardL

                2,3381929




                2,3381929






























                    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%2f53424190%2fcontinuing-xml-parsing-if-tag-not-found-in-python-using-minidom%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

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    Refactoring coordinates for Minecraft Pi buildings written in Python