gpt4 book ai didi

java - Xml 文档读取尝试错误

转载 作者:行者123 更新时间:2023-12-01 17:12:40 27 4
gpt4 key购买 nike

在我的软件中,我试图创建一个返回 xml 文件任何位的类,看看代码和它给我的错误,我不知道如何纠正它:(

XML:

<everConfigured>
<value>false</value>
</everConfigured>

<ServerPort>
<value>9000</value>
</ServerPort>

<ClientPort>
<value>8000</value>
</ClientPort>

XML 阅读器类:

 public static String getValue(String Path,String Tag,String Atribute) throws IOException, SAXException, ParserConfigurationException
{
File fXmlFile = new File(Path);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName(Tag);
Node nNode = nList.item(0);
Element eElement = (Element) nNode;
return eElement.getAttribute(Atribute);
}

我是这样调用它的:

public static void main(String[] args) throws SocketException, IOException, SAXException, ParserConfigurationException {
System.out.println(
XMLRead.getValue("/home/ghhwer/Desktop/settings.xml", "everConfigured","value"));
}

但返回此错误:

[Fatal Error] settings.xml:5:2: The markup in the document following the root element must be well-formed.
Exception in thread "main" org.xml.sax.SAXParseException; systemId: file:/home/ghhwer/Desktop/settings.xml; lineNumber: 5; columnNumber: 2; The markup in the document following the root element must be well-formed.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:348)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:205)
at program.XMLRead.getValue(XMLRead.java:20)
at program.Start.main(Start.java:12)

最佳答案

The markup in the document following the root element must be well-formed.

XML 的格式良好有几个规则:

  1. 所有 XML 元素都必须有结束标记;
  2. 标签大小写应相同;
  3. XML 元素必须正确嵌套;
  4. XML 文档必须有根元素
  5. XML 属性值必须加引号;
  6. 某些符号具有特殊含义,必须转义(>、<、&、'、")。

在提供的 XML 片段中缺少根元素,这就是解析器提示的原因。因此,格式良好的 XML 将是:

<?xml version="1.0" encoding="UTF-8"?>
<config>
<everConfigured>
<value>false</value>
</everConfigured>

<ServerPort>
<value>9000</value>
</ServerPort>

<ClientPort>
<value>8000</value>
</ClientPort>
</config>

参见http://www.w3schools.com/xml/xml_syntax.asp作为 XML 语法引用。

关于java - Xml 文档读取尝试错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23172342/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com