Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - How to check if string is a valid XML element name?

Tags:

java

xml

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:

  1. Names can contain letters, numbers, and other characters
  2. Names cannot start with a number or punctuation character
  3. Names cannot start with the letters xml (or XML, or Xml, etc)
  4. Names cannot contain spaces

I found other questions that offered regex solutions, isn't there a function that already does that?

like image 868
ekeren Avatar asked Mar 22 '11 18:03

ekeren


2 Answers

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);
}
like image 66
roghughe Avatar answered Oct 23 '22 01:10

roghughe


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.

like image 24
lavinio Avatar answered Oct 23 '22 00:10

lavinio