gpt4 book ai didi

Java Dom 获取属性

转载 作者:行者123 更新时间:2023-11-30 04:24:17 25 4
gpt4 key购买 nike

我正在尝试解析 xml 文件,但它不会打印属性值。我不知道如何从手机获取属性类型

 try {  String subor = "Noviny.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(subor);
System.out.println("----------------\n");
NodeList nodelist = document.getElementsByTagName("Author");
NodeList nodelist1 = document.getElementsByTagName("Article");
for(int i = 0; i < nodelist.getLength(); i++) {
Node uzol = nodelist.item(i);
if (uzol.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) uzol;
System.out.println("Id:" + element.getElementsByTagName("Id").item(0).getTextContent() + "\n");
System.out.println("Name:" + element.getElementsByTagName("Name").item(0).getTextContent() + "\n");
System.out.println("Email:" + element.getElementsByTagName("Email").item(0).getTextContent() + "\n");
System.out.println("typ: " + element.getAttribute("typ") + "\n");
System.out.println("phone:" + element.getElementsByTagName("phone").item(0).getTextContent() + "\n");
System.out.println("typ: " + element.getAttribute("typ") + "\n");
System.out.println("sal: " + element.getElementsByTagName("sal").item(0).getTextContent() + "\n");
}


catch (Exception e) {
e.printStackTrace();
}

和 xml

<Noviny>
<Author>
<Id>1</Id>
<Name>first</Name>
<Email>first@gmail.com</Email>
<phone typ="mobil">09443916565</phone>
<sal>500</sal>
</Author>
<Author>
<Id>2</Id>
<Name>second</Name>
<Email>second@gmail.com</Email>
<phone typ="pevna">094415665465</phone>
<sal>1000</sal>
</Author>

还有一件事:是否可以只打印 (System.out.println) xml 文件的树表示形式?

谢谢

最佳答案

您当前正在请求typ <Author> 的属性元素(由于某种原因两次)。您应该获取 <phone>元素(您已经在这样做),然后请求 typ that 元素的属性,而不是 <Author>元素。

关于Java Dom 获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16307311/

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