gpt4 book ai didi

Java Dom API getAttribute

转载 作者:行者123 更新时间:2023-12-01 14:37:52 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 文件的树表示形式?

谢谢

最佳答案

element 是一个 Author 元素节点,没有属性。 typ 属性位于 phone 标记

Element phone = (Element)element.getElementsByTagName("phone").item(0);
System.out.println("typ: " + phone.getAttribute("typ") + "\n");

对于第二部分,请尝试

Element root = document.getDocumentElement();
System.out.println(root.toString());

关于Java Dom API getAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16311521/

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