java的<user id = "02" name = "赵敏" password = "wuji" address = "光明顶" sex = "女"/>这种写法读不出数据
时间: 2023-10-16 17:31:12 浏览: 150
java字符串-用户名和密码-加密解密
5星 · 资源好评率100%
这段代码看起来像是XML格式的,但是缺少了根节点,无法正确解析数据。可以将这段代码放入一个XML文件中,并添加根节点,例如:
```
<users>
<user id="02" name="赵敏" password="wuji" address="光明顶" sex="女"/>
</users>
```
然后通过解析XML文件来读取数据。在Java中,可以使用JAXP库来解析XML文件,例如使用DOM Parser:
```java
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File inputFile = new File("input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("user");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String id = eElement.getAttribute("id");
String name = eElement.getAttribute("name");
String password = eElement.getAttribute("password");
String address = eElement.getAttribute("address");
String sex = eElement.getAttribute("sex");
System.out.println("User id : " + id);
System.out.println("Name : " + name);
System.out.println("Password : " + password);
System.out.println("Address : " + address);
System.out.println("Sex : " + sex);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个示例会输出XML文件中的每个用户的id、name、password、address和sex属性。
阅读全文