所以,我想使用nodelist和documentbuilder解析我的Android应用程序中的XML文件。问题是,Documentbuilder.parse()总是返回null,并最终抛出一个IOException。我猜这与文件路径错误有关。Android XML解析,Documentbuilder抛出异常
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异常是:“找不到协议:EquiScore /资产/协议/ LC1_2008.xml” “MalformedURLException的”
我试过文件名的各种变化,但无论如何似乎得到这个错误。
谢谢你,至少这让我到一个“找不到文件”的错误! :) 现在我只需要找出我的文件的路径。 它位于assets/Protocols /中,但似乎不起作用。 – Bentebent
那么,通过AssetManager API访问资产(资产/文件夹中的东西) - 不是文件或URL。 – Jens
好吧,那么最好的行动是什么?创建一个新文件夹,类似res/XML/Protocols,并从那里获取? 编辑:嗯,我正在尝试这个,但无法让它找到文件。我必须考虑关于文件路径或整个事情的错误方式? – Bentebent