我有一个 XML 文档,其中包含带前导零的字符串。当我使用 XmlResourceParser 迭代 XML 文件时,我注意到带有前导零的字符串在调用 getAttributeValue 时被修改,删除了前导零。此功能在过去有效,我只是在升级到 Android Studio 3.x 后才注意到。为了让“getAttributeValue”保留前导零,我需要做些什么特别的事情吗?
这是我正在使用的测试 XML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<FictionalSpies>
<Property Country="Great Britain" Agency="MI6">
<Item FullName="James Bond" AgentCode="007" />
<Item FullName="John Wolfgramm" AgentCode="0010" />
<Item FullName="Sam Johnston" AgentCode="0012" />
</Property>
<Property Country="United States" Agency="CONTROL">
<Item FullName="Maxwell Smart" AgentCode="86" />
<Item FullName="Unknown" AgentCode="99" />
<Item FullName="The Chief" AgentCode="Q" />
</Property>
<Property Country="United States" Agency="MiB">
<Item FullName="James Darrell Edwards III" AgentCode="J" />
<Item FullName="Kevin Brown" AgentCode="K" />
<Item FullName="Derrick Cunningham" AgentCode="D" />
</Property>
</FictionalSpies>
这是列表中每个“间谍”的日志打印输出。如您所见,前三个在其 AgentCode 中丢失了“00”。例如,詹姆斯邦德的代理人代码应该是“007”而不是“7”。
D/XMLTest: Great Britain MI6 James Bond 7
D/XMLTest: Great Britain MI6 John Wolfgramm 10
D/XMLTest: Great Britain MI6 Sam Johnston 12
D/XMLTest: United States CONTROL Maxwell Smart 86
D/XMLTest: United States CONTROL Unknown 99
D/XMLTest: United States CONTROL The Chief Q
D/XMLTest: United States MiB James Darrell Edwards III J
D/XMLTest: United States MiB Kevin Brown K
D/XMLTest: United States MiB Derrick Cunningham D
这是连接到表单上的按钮按下并迭代生成先前日志消息的 XML 的代码:
public void buttonOnClick(View v)
{
int eventType = -1;
String name;
String country = null;
String agency = null;
String fullName = null;
String agentCode = null;
try
{
XmlResourceParser xmlRP = getResources().getXml(R.xml.test);
while (eventType != XmlResourceParser.END_DOCUMENT)
{
if (eventType == XmlResourceParser.START_TAG)
{
name = xmlRP.getName();
if (name.contentEquals("Property"))
{
country = xmlRP.getAttributeValue(null, "Country");
agency = xmlRP.getAttributeValue(null, "Agency");
} else if (name.contentEquals("Item"))
{
fullName = xmlRP.getAttributeValue(null, "FullName");
agentCode = xmlRP.getAttributeValue(null, "AgentCode");
Log.d("XMLTest", country + " " + agency + " " + fullName + " " + agentCode );
}
}
eventType = xmlRP.next();
}
} catch (XmlPullParserException e)
{
} catch (IOException e)
{
}
}