gpt4 book ai didi

java - 如何使用 XMLReader 解析 xml 文件

转载 作者:行者123 更新时间:2023-11-29 06:17:00 24 4
gpt4 key购买 nike

我有一个“contacts.xml”文件,它的结构是:

<?xml version="1.0" encoding="UTF-8"?>
<Contacts>
<Contact>
<ContactId>1</ContactId>
<ContactName>Aditya Kothari</ContactName>
<MobilePhone1>NA</MobilePhone1>
<MobilePhone2>NA</MobilePhone2>
<OfficePhone1>NA</OfficePhone1>
<OfficePhone2>NA</OfficePhone2>
<OfficePhone3>NA</OfficePhone3>
<HomePhone1>999-367-3944</HomePhone1>
<HomePhone2>NA</HomePhone2>
<TokenId>mtn</TokenId>
</Contact>
<Contact>
<ContactId>2</ContactId>
<ContactName>Jai Mandloi </ContactName>
<MobilePhone1>NA</MobilePhone1>
<MobilePhone2>NA</MobilePhone2>
<OfficePhone1>NA</OfficePhone1>
<OfficePhone2>NA</OfficePhone2>
<OfficePhone3>NA</OfficePhone3>
<HomePhone1>800-742-9678</HomePhone1>
<HomePhone2>NA</HomePhone2>
<TokenId>mtn</TokenId>
</Contact>
</Contacts>

现在我正在做这个-

File xmlFile = new File("E:\\contacts.xml");
InputStream is = new FileInputStream(xmlFile);
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(is);
while(reader.hasNext())
{
if(reader.hasText()
{
System.out.println(reader.getText());
}
reader.next();
}

我不想要 xml 的“ContactId”和“TokenId”元素的值。我应该如何编码?

最佳答案

最近我是这样的-

while(reader.hasNext())
{
if(reader.getEventType()==XMLStreamConstants.START_ELEMENT)
{
if(!reader.getLocalName().equals("ContactId") && !reader.getLocalName().equals("TokenId") && !reader.getLocalName().equals("Contacts") && !reader.getLocalName().equals("Contact"))
{
System.out.println(reader.getElementText());
}
}
reader.next();
}

关于java - 如何使用 XMLReader 解析 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4734365/

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