gpt4 book ai didi

java - 如何获取xml节点?

转载 作者:行者123 更新时间:2023-12-02 10:24:36 25 4
gpt4 key购买 nike

下面是我的 xml,它将位于设备的一个文件夹中,我将读取该 xml 文件。如何使用 XmlPullParser 在 android 中获取/读取或返回 xml 节点。

<?xml version="1.0" encoding="utf-8"?>
<appLayouts>
<AIRLINE_FORM sendSelectionEvent="false">
<RESULT multiSelect="false"></RESULT>
</AIRLINE_FORM>
<ALLOWANCES_FORM sendTableEditEvent="false" sendSelectionEvent="true">
<RESULT multiSelect="false">
<field header="Category" size="75" align="left" edit="false"></field>
<field header="Allowance" size="-1" align="left" edit="false"></field>
</RESULT>
</ALLOWANCES_FORM>
</appLayouts>

因此,如果我将 AIRLINE_FORM 作为 xml 节点,我只想返回 AIRLINE_FORM 的完整 xml 节点,即它必须返回:

<AIRLINE_FORM sendSelectionEvent="false">
<RESULT multiSelect="false"></RESULT>
</AIRLINE_FORM>

我试过了

public String parseXML(String sTargetName)
{
String XmlNode = "";
try {
int eventType = parser.getEventType();

while (eventType != XmlPullParser.END_DOCUMENT) {
String name;
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equals(sTargetName)) {
XmlNode = parser.getText();
//parser.getAttributeValue(null,"id");
Log.d("Task2/Parser", "Start tag: "+parser.getName());

Log.d("Task2/Parser", "Start tag -text: "+parser.getText());
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
Log.d("Task2/Parser", "End tag: "+parser.getName());
case XmlPullParser.TEXT:
Log.d("Task2/Parser", "Text "+parser.getText());

}
eventType = parser.next();
}
}catch (XmlPullParserException ex){
//AppLog.WriteMessage(AppLog.LogType.ERROR, ex.Message);
Log.d("Log_d"," Exception: "+ ex.toString());
}
catch (IOException ex){
//AppLog.WriteMessage(AppLog.LogType.ERROR, ex.Message);
Log.d("Log_d"," Exception: "+ ex.toString());
}
return XmlNode;
}

最佳答案

您需要传递要访问的每个节点的节点名称。这是帮助您获取节点的代码

public String getValue(Element item, String str) {      
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}

public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}

关于java - 如何获取xml节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54070255/

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