1

i have an xml as below.

<stat>
    <Parents>
        <Parent>
            <parentName></parentName>
            <occupation></occupation>
        </Parent>
        <Parent>
            <parentName>Brian</parentName>
            <occupation>Doctor</occupation>
        </Parent>
    </Parents>
     <Parents/>
    <Parents>
        <Parent>
            <parentName></parentName>
            <occupation></occupation>
        </Parent>
        <Parent/>
    </Parents>
</stat>

I need to validate the xml file using java in based on the parents values.When ever the xml file contains empty parents block for e.g: <Parents/> or <Parents> <Parent><parentName></parentName><occupation></occupation></Parent></Parents>.I need to throw an exception saying xml is not valid.How to implement the requirment using either xpath or some approach with out performance issue. Your help appreciated.

4
  • 3
    What have you attempted? Commented Jul 5, 2011 at 18:36
  • You could do this with regex easily. Try it out and then let's see how we can help. Commented Jul 5, 2011 at 18:37
  • First Link of google search (xpath get nodes with empty text) looks useful. Commented Jul 5, 2011 at 18:44
  • 5
    No, please do NOT even think of using regexps. XML should be handled with XML tools, since raw textual representation != logical model. Besides, regexps actually can not easily even deal with matching of start/end tags; that's DFA 101 fact Commented Jul 5, 2011 at 18:51

2 Answers 2

1

First, I'd recommend you to take a look on XSD. Using XSD you can define which tags and how many such tags may appear in your XML. Once you are done just validate XML: http://download.oracle.com/javaee/1.4/tutorial/doc/JAXPDOM8.html

d
Sign up to request clarification or add additional context in comments.

Comments

0

Aside from XSD or RelaxNG schemas (which should allow specifying acceptable models; and empty one not being one of them, can report it), this would be easy to deal with Stax XMLStreamReader (javax.xml.stream.) as well. Read any tutorial, and check for START_ELEMENT/END_ELEMENT pairs (with 'parents' as local name).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.