3

I need to parse XML Tags which are commented out like

<DataType Name="SecureCode" Size="4" Type="NVARCHAR">
    <!-- <Validation>
            <Regex JavaPattern="^[0-9]*$" JSPattern="^[0-9]*$"/>
    </Validation> -->
    <UIType Size="4" UITableSize="4"/>
</DataType>

But all I found was setIgnoringComments(boolean)

Document doc = docBuilder.parse(new File(PathChecker.getDataTypesFile()));
docFactory.setIgnoringComments(true); // ture or false, no difference

But it doesn't seem to change anything. Is there any other way to parse this comments? I have to use DOM.

Regards

4
  • Possible duplicate of : stackoverflow.com/questions/12069509/… Commented Nov 15, 2013 at 8:28
  • 1
    I've also found that post. It doesn't help me in any way. Commented Nov 15, 2013 at 8:29
  • It appears that setIgnoringComments() has a bug, it has been reported, but no fix has been made in all these years: issues.apache.org/jira/browse/XERCESJ-37 Commented Mar 11, 2018 at 1:18
  • setIgnoringComments() just worked for me Commented May 6, 2021 at 13:58

2 Answers 2

5

Method "setIgnoringComments" removed comments from DOM tree during parsing. With "setIgnoringComments(false)" you can get comment text like:

    NodeList nl = doc.getDocumentElement().getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        if (nl.item(i).getNodeType() == Element.COMMENT_NODE) {
            Comment comment=(Comment) nl.item(i);
            System.out.println(comment.getData());
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Oh that's cool. Didn't tried it but that should solve it. Thanks
This will not pick single-line comments.
0

Since there seems not to exist a "regular way" of solving the problem I've just removed the comments.

BufferedReader br = new BufferedReader(new FileReader(new File(PathChecker.getDataTypesFile())));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(PathChecker.getDataTypesFileWithoutComments())));

String line = "";

while ((line = br.readLine()) != null) {
    line = line.replace("<!--", "").replace("-->", "") + "\n";
    bw.write(line);
}

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.