【问题标题】:Android - Test For "Well Formed" Valid XML on importAndroid - 在导入时测试“格式良好”的有效 XML
【发布时间】:2014-01-04 15:16:23
【问题描述】:

我在启动时将标准 XML 导入到我的应用程序中,用于保存和调用应用程序参数。

XML 会在 onPause() 中更新,但是如果应用程序因任何原因崩溃,则生成的 XML 可能无效。

我希望能够测试 XML 是否有效,如果无效则使用通用设置。

问:如何测试 XML 是否有效?

示例 XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<DecisionList>
 <ExampleSet1>
  <Value1> 1.0 </Value1>
 </ExampleSet1>
</DecisionList>

主要活动

public class MyActivity  extends Activity  implements OnItemSelectedListener{
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        MyActivity_Preflight.Setup();
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
     // .......
 }
 }

飞行前活动

public class MyActivity_Preflight {

public static void Setup() throws Exception{

try{
XPathFactory  factory=XPathFactory.newInstance();
XPath xPath=factory.newXPath();

File pathTmp = new File(Environment.getExternalStorageDirectory() + "/myApp/Tmp" );
File xmlDocument = new File( pathTmp + "/tmp.xml");

/*
*  Chk to see if XML is Valid Statement block Here
*    if Valid then Continue
*/

InputSource inputSource = new InputSource(new FileInputStream(xmlDocument));
XPathExpression  tag_Value1 = xPath.compile("/DecisionList/ExampleSet1/Value1");
String Value1 = tag_Value1.evaluate(inputSource);
GlobalVariables.setSeekBarValue1(Float.valueOf(Value1));

// if (XMLisNotValid)
// GlobalVariables.setSeekBarValue1(1.0f);

  }
 }
}

感谢您的宝贵时间。

【问题讨论】:

    标签: java android xml validation


    【解决方案1】:

    您可以使用DocumentBuilderFactory进行验证

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.parse(pathTmp + "/tmp.xml");
    

    如果 XML 解析,那么它是一个有效的 XML,如果不是,它不是一个有效的 XML。

    【讨论】:

    • 感谢 Jayamohan,我将如何返回 documentBuilderFactory 解析方法的真或假布尔输出。即,如果它解析则为真。谢谢。
    • 如果 XML 中有任何问题,您应该根据 API 获得 SAXException
    • 再次感谢,您能否给我一个在给出格式错误的 XML 时处理 SAXException 的示例,而我可以从其他方法加载设置。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    相关资源
    最近更新 更多