gpt4 book ai didi

java - 如何使用此路径读取 xml 字符串值,如代码所示(getFilesDir().getAbsolutePath()+ File.separator + "test.xml")

转载 作者:行者123 更新时间:2023-12-02 08:16:33 27 4
gpt4 key购买 nike

大家好,

我是 Android 新手。我正在使用 DOM 解析来读取 xml 字符串值。为此,我使用了以下代码,该代码将在给出异常之后获取根元素值,请解决此问题,

提前致谢,

XML 代码:

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<ChangePassword>
<Oldpassword>23545565635354</Oldpassword>
<Newpassword>addsffggfdsfdsfdfs </Newpassword>
</ChangePassword>

java代码:

   File file = new File(getFilesDir().getAbsolutePath()+ File.separator + "test.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("ChangePassword");
System.out.println("Information of all entries");

for (int s = 0; s < nodeLst.getLength(); s++) {

Node fstNode = nodeLst.item(s);

if (fstNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fstElmnt = (Element) fstNode;

// Firstname
NodeList fstNmElmntLst = ((Document) fstElmnt).getElementsByTagName("Oldpassword");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = ((Node) fstNmElmnt).getChildNodes();
System.out.println("Old password : " + ((Node) fstNm.item(0)).getNodeValue());

// Lastname
NodeList lstNmElmntLst = ((Document) fstElmnt).getElementsByTagName("Newpassword");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = ((Node) lstNmElmnt).getChildNodes();
System.out.println("Old password : " + ((Node) lstNm.item(0)).getNodeValue());

// Address
NodeList addrNmElmntLst = ((Document) fstElmnt).getElementsByTagName("Newpassword");
Element addrNmElmnt = (Element) addrNmElmntLst.item(0);
NodeList addrNm = ((Node) addrNmElmnt).getChildNodes();
System.out.println("Address : " + ((Node) addrNm.item(0)).getNodeValue());
}
}
} catch (Exception e) {
Log.e("Exception",e.toString());
//e.printStackTrace();
}

最佳答案

哇。 DOM 解析器代码非常丑陋。请只是try Simple XML instead 。看看你的代码可能是什么样的:

@Root(name = "ChangePassword")
public class PasswordChange {
@Element(name = "Oldpassword")
public String oldPassword;

@Element(name = "Newpassword")
public String newPassword;
}

这样就好多了。然后你可以说:

Serializer serial = new Persister();
PasswordChange pc = serial.read(PasswordChange.class, streamOrFileWithXML);

这就是全部内容了。不过,如果您想了解如何将其包含在 Android 中,请查看 look at my blog post .

关于java - 如何使用此路径读取 xml 字符串值,如代码所示(getFilesDir().getAbsolutePath()+ File.separator + "test.xml"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6290926/

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