do you know function in java that will validate a string to be a good XML element name.
Form w3schools:
XML elements must follow these naming rules:
- Names can contain letters, numbers, and other characters
- Names cannot start with a number or punctuation character
- Names cannot start with the letters xml (or XML, or Xml, etc)
- Names cannot contain spaces
I found other questions that offered regex solutions, isn't there a function that already does that?
Using the org.apache.xerces utilities is a good way to go; however, if you need to stick to Java code that's part of the standard Java API then the following code will do it:
public void parse(String xml) throws Exception {
XMLReader parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(new DefaultHandler());
InputSource source = new InputSource(new ByteArrayInputStream(xml.getBytes()));
parser.parse(source);
}
If you are using Xerces XML parser, you can use the XMLChar (or XML11Char) class isValidName()
method, like this:
org.apache.xerces.util.XMLChar.isValidName(String name)
There is also sample code available here for isValidName
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With