Java 为什么我的代码没有像这里那样将给定字符串解析为xml?它不是重复的,因为我也使用了现有答案的帮助,但可以';我不能纠正它 publicstaticvoidmain(字符串[]args)抛出SAXException、ParserConfiguration异常、IOException { 字符串fXml=“\n”+ “\n”+ “Pankaj\n”+ “25\n”+ “开发人员\n”+ “男性\n”+ ""; DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder=dbFactory.newDocumentBuilder(); documentdoc=dBuilder.parse(fXml); doc.getDocumentElement().normalize(); System.out.println(“根元素:+doc.getDocumentElement().getNodeName()); }

Java 为什么我的代码没有像这里那样将给定字符串解析为xml?它不是重复的,因为我也使用了现有答案的帮助,但可以';我不能纠正它 publicstaticvoidmain(字符串[]args)抛出SAXException、ParserConfiguration异常、IOException { 字符串fXml=“\n”+ “\n”+ “Pankaj\n”+ “25\n”+ “开发人员\n”+ “男性\n”+ ""; DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder=dbFactory.newDocumentBuilder(); documentdoc=dBuilder.parse(fXml); doc.getDocumentElement().normalize(); System.out.println(“根元素:+doc.getDocumentElement().getNodeName()); },java,xml,Java,Xml,我收到以下错误: 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" + " <na

我收到以下错误:

 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());
    }
线程“main”java.net.MalformedURLException中的异常:无协议:
我如何让工作变得直观?是的,问题出在第一行,但我不确定如何纠正这一点。

您需要使用InputStream将xml发送到解析器,而不是字符串本身。试试这个:

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

您使用的
parse
方法是解析位于URI参数处的XML文件(String参数表示URI,而不是XML字符串)。因此,它基本上是“如何解析XML字符串?”的重复。
    Document doc = dBuilder.parse(new InputSource(new  ByteArrayInputStream(fXml.getBytes("utf-8"))));