phax / ph-schematron

Java Schematron library that supports XSLT and native application
Apache License 2.0
115 stars 36 forks source link

How do I determine if a tag contains an attribute before I check it? #131

Closed mshen6666 closed 2 years ago

mshen6666 commented 2 years ago

Hi Philip, I want to check if an xml tag contains an attribute before making a judgment on it.like I want to check the item tag,but it has two formats. one of them like <item root="xxxxxxxxxxx" extension="$"/>,another one like <item><part value="name"/></item>,i just want to check who has attribute with extension . how should i write sch file.now my sch file like `

extension not contain '$' ` thx
phax commented 2 years ago

Hi, Without being the biggest XPath specialist on the planet, I suggest you try this one:

<sch:pattern>
  <sch:rule context="//item[@extension]">
    <sch:assert test="contains(@extension,'$')">extension not contain '$'</sch:assert>
  </sch:rule>
</sch:pattern>

Edit: for performance reasons at runtime, it would be better to replace // in //item[@extension] with the paths it can appear in as e.g.

  <sch:rule context="/path/a/item[@extension] | /path/b/item[@extension]">

Of course, if there are too many path, "//item" is easiest to read and maintain

hth

mshen6666 commented 2 years ago

Thank you very much for your prompt reply, I will try it!