Java – string substitution in substring

I want to write a method for a Java class This method accepts the XML data string given below as input

<?xml version="1.0" encoding="UTF-8"?>
<library>

    <book>
        <name> <> Programming in ANSI C <> </name>
        <author> <>  Balaguruswamy <> </author>
        <comment> <> This comment may contain xml entities such as &,< and >. <> </comment>
    </book>

    <book>
        <name> <> A Mathematical Theory of Communication <> </name>
        <author> <> Claude E. Shannon <> </author>
        <comment> <> This comment also may contain xml entities. <> </comment>
    </book>

    <!-- This library contains more than ten thousand books. -->
</library>

XML strings contain many substrings that begin and end with < > Substrings can contain XML entities, such as >, <, &, 'and ". This method needs to replace them with & gt;, & lt;, & amp;. & and & respectively. Are there any regular expression methods in Java to complete this task?

Solution

Is this data passed to you, or can you control it? If so, I recommend using CDATA blocks If you are really unsure about the data entered into the XML block, just wrap everything in CDATA and save it to the database

If you can't control this, as far as I know, it will require considerable coding due to the number of edge cases you may need to deal with Not something that a simple regular expression can handle (if a valid block starts, if a block ends, if a block has ended, etc.)

This is a very basic regular expression case of < >, but the rest I really believe just becomes very complex

\<\>* //For <> changes
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>