所以,我正在尝试使用nodelist和documentbuilder解析我的Android应用中的XML文件。问题是,Documentbuilder.parse()总是返回null并最终抛出IOException。我猜它与文件路径错误有关。
public class EquiScoreActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ProtocolFactory.GetProtocolFactory().LoadProtocol("EquiScore/assets/Protocols/LC1_2008.xml");
}
}
public class ProtocolFactory
{
private static ProtocolFactory m_Instance = new ProtocolFactory();
Document dom;
private ProtocolFactory()
{
}
public static ProtocolFactory GetProtocolFactory()
{
return m_Instance;
}
public Protocol LoadProtocol(String filename)
{
Protocol output = null;
List<JudgementGroup> jGroups;
List<GeneralAssesment> gAssesment;
ParseXmlFile(filename);
ParseDocument();
return output;
}
private void ParseXmlFile(String filename)
{
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try
{
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
dom = db.parse(filename);
}
catch(ParserConfigurationException pce)
{
pce.printStackTrace();
}
catch(SAXException se)
{
se.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
基本上我需要知道如何获得正确的文件路径或其他(可能更好?)方式来解析XML。一种类型的每个节点可以有不同数量的子节点,这就是我认为这种方法很好的原因。
IOException是: “MalformedURLException的” “未找到协议:EquiScore / assets / Protocols / LC1_2008.xml”
我尝试过各种各样的文件名,但无论如何似乎都会出现这种错误。
答案 0 :(得分:2)
您收到的IOException
是由于您传递的内容是一个裸路径名而DocumentBuilder.parse()
需要一个网址。
网址的第一部分称为“协议”(它是http
中的http://www.google.com
)。您的路径名未指定协议,因此错误显示“未找到协议”。您可以通过将file://
添加到路径名中来创建路径名。
或者,您可以创建File
或FileInputStream
对象,并将其传递给DocumentBuilder.parse()
,因为该方法已超载。例如:
dom = db.parse(new File(filename));
编辑:由于您的文件位于assets/
文件夹中,因此可以使用AssetManager.open()
返回InputStream
,而DocumentBuilder.parse()
又被AssetManager assetManager = ...
dom = db.parse(assetManager.open("Protocols/LC1_2008.xml"));
的一个重载版本接受:
{{1}}
答案 1 :(得分:1)
显然,您已将XML放在assets文件夹中,因此您应使用AssetManager
检索要解析的InputStream
。
这样的事情:
Context context = ...;
AssetManager assManager = context.getAssets();
DocumentBuilder db = ..;
db.parse(assManager.open("Protocols/LC1_2008.xml"));