1
 public static void main(String[] args) throws SAXException, ParserConfigurationException, IOException
    {
        String fXml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<Emp id=\"1\">\n" +
"    <name>Pankaj</name>\n" +
"    <age>25</age>\n" +
"    <role>Developer</role>\n" +
"    <gen>Male</gen>\n" +
"</Emp>";
       DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXml);

    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    }

I am getting the following errors:

Exception in thread "main" java.net.MalformedURLException: no protocol: <?xml version="1.0" encoding="UTF-8" standalone="yes"?>

How do I make work as intuitive? Yeah the problem lies in the very first line but I am not sure how to correct this.

Ulsa Minor
  • 89
  • 1
  • 10
  • The `parse` method you are using, is to parse a XML file located at the URI parameter (the String parameter represents an URI, not a XML String) . So basically it is a duplicate of "How can I parse a XML String ?" . – Arnaud Jun 27 '16 at 12:51

1 Answers1

1

You need to send the xml to the parser with an InputStream and not the string itself. Try this:

    Document doc = dBuilder.parse(new InputSource(new  ByteArrayInputStream(fXml.getBytes("utf-8"))));
SCouto
  • 7,808
  • 5
  • 32
  • 49