On this page:
2.1 Basic Usage
2.2 Hierachy
2.3 Default Attribute
2.4 Entity Convert

2 xml-to-hash🔗ℹ

(xml-file-to-hash (-> path-string? (listof (cons/c string? (or/c 'v 'a))) hash?))

2.1 Basic Usage🔗ℹ

xml:
<empty attr1="a1" attr2="a2">v</empty>

xml-to-hash:
(let ([xml_hash (xml-file-to-hash
                 empty2_xml_file
                 '(
                   "empty"
                   "empty.attr1"
                   "empty.attr2"
                   )
                )])
 
  (printf "xml hash has ~a keys.\n" (hash-count xml_hash))
 
  (printf "empty's count: ~a\n" (hash-ref xml_hash "empty's count"))
 
  (printf "empty's value: ~a\n" (hash-ref xml_hash "empty1"))
 
  (printf "empty.attr1: ~a\n" (hash-ref xml_hash "empty1.attr11"))
 
  (printf "empty.attr2: ~a\n" (hash-ref xml_hash "empty1.attr21")))
 
xml hash has 4 keys.
empty's count: 1
empty's value: v
empty.attr1: a1
empty.attr2: a2

Be careful, if xml is below style, then node "empty"’s value is "".
<empty attr1="a1" attr2="a2"/>

2.2 Hierachy🔗ℹ

XML is a hierachy structure text format. So, xml-to-hash refect the hierachy information. You access a node’s attribute or content, you should give all the ancester’s name in order.

xml:
<level1>
  <level2>
    <level3 attr="a3">
      <level4>Hello Xml!</level4>
    </level3>
  </level2>
</level1>

(let ([xml_hash (xml-file-to-hash
                 "hierachy.xml"
                 '(
                   "level1.level2.level3.attr"
                   "level1.level2.level3.level4"
                   ))])
 
  (printf "level1.level2.level3.attr: [~a]\n" (hash-ref xml_hash "level11.level21.level31.attr1"))
 
  (printf "level1.level2.level3.level4: [~a]\n" (hash-ref xml_hash "level11.level21.level31.level41"))
)
 
level1.level2.level3.attr: [a3]
level1.level2.level3.level4: [Hello Xml!]

2.3 Default Attribute🔗ℹ

If some node has no some attribute, then the value is not exists.

xml:
<list>
  <child attr="a1">c1</child>
  <child>c2</child>
  <child attr="a3">c3</child>
</list>

(let ([xml_hash (xml-file-to-hash
                 "default.xml"
                 '(
                   "list.child.attr"
                   ))])
 
  (printf "list1.child1.attr1: [~a]\n" (hash-ref xml_hash "list1.child1.attr1"))
 
  (printf "list1.child1.attr2: [~a]\n" (hash-ref xml_hash "list1.child1.attr2" ""))
)
 
list1.child1.attr1: [a1]
list1.child1.attr2: []

2.4 Entity Convert🔗ℹ

There are two kinds of entity:

1. numeric character reference

&#xhhhh; or &#nnnn;

where the x must be lowercase in XML documents, hhhh is the code point in hexadecimal form, and nnnn is the code point in decimal form.

2. 5 predefined name

&name;

&amp;[&], &lt;[<], &gt;[>], &apos;['], and &quot;["].

when reading from xml, attributes and values will be convert from entity to specific character.

when writing to xml, in attributes and values, 5 special chars will be converted to entity string.