dongyoucha0645 2013-04-09 21:08
浏览 46

在PHP中验证XML并生成“人类可读”的错误消息?

I'm trying to build a tool for validating specific XML and outputting human-readable results. My existing PHP code uses DOMDocument::schemaValidate to validate the XML against a .xsd file, but the error messages aren't very friendly.

For example, Let's pretend my XML looks like the sample below and that Latitude should be a decimal:

<Person>
  <FirstName>Bret</FirstName>
  <Location>
    <Address>123 Test Ave.</Address>
    <Latitude></Latitude>
    <Longitude>30.139338</Longitude>
  </Location>
</Person>

The error message I would currently get would be:

Document::schemaValidate(): Element 'Latitude': '' is not a valid value of the atomic type 'xs:decimal'.

I want it to say:

Error in XML Line #5: The person "Bret" has an empty Latitude in their address. You must include a valid Latitude in order for us to process this XML.

Similar questions has been asked before:

However, I'm willing to write my own brute-force validation code using PHP or Perl if DOMDocument::schemaValidate isn't the right tool for this job. Notice that my error messages need to refer to information stored in parent elements, like the "FirstName" field in my example.

My question is: What's a good approach to create this validation tool? Are there any existing code libraries or tutorials to point me in the right direction?

Thanks!!

  • 写回答

1条回答 默认 最新

  • douwo1862 2013-04-10 09:04
    关注

    As you can imagine this is specific to each XML file and format.

    The first problem I would start to work with is to identify the exact element that relates to the validation error. E.g. with your error that is

    /Person/Location/Latitude
    

    This would be a pre-condition to tell in an error message that something is wrong with a specific person (element).

    The second problem is to keep record of the main building blocks of your structure.

    E.g. it's known that Latitude is part of Location which is part of Person. This knowledge you need to manage somewhere to give better error messages.

    Also I would do both, e.g. outputting a more friendly error message as well as the more technical one. Also take care that you can not always solve your problem. E.g. if in the input a Person is given the wrong tagname like person you can never resolve this to a human friendly error message, because this is out of the knowledge you can add.

    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)