Accessing Data in XML Form

An E-Mail Address Widget described how to access a single source value using a Field object, its Binding property and a source path. For the photograph widget, the source value is no longer a simple string, instead it is an XML document. The approach used for the e-mail address widget needs to be extended to allow values embedded in the XML document to be retrieved individually. Support is provided for accessing data in an XML by extending the source path. The code to retrieve the person's name and unique identifier from the XML document is shown below.

Figure 1. Getting the Person Name and ID Values
String personID = context.getDataAccessor()
      .get(component.getBinding()
          .getSourcePath().extendPath("photo/id"));
    String personName = context.getDataAccessor()
        .get(component.getBinding()
            .getSourcePath().extendPath("photo/name"));

The source path is retrieved from the field's binding in the same way as the e-mail address widget in the previous chapter. However, the source path is not passed directly to the get method of the data accessor retrieved from the context . Doing this would simply return the entire XML document as a string. Instead the source path is first extended using the extendPath method. The path extensions are photo/id and photo/name. They correspond directly to the tree structure of the XML document. For example, the photo/id path means the data accessor will retrieve the body content of the id element which is a child of the photo element. In the sample XML above, this is the value "101". Those familiar with XPATH will recognize the format of these paths. However, while the extended paths used here are similar, they are not XPATH. Creating simple XML documents where each value is represent in the body content of an element will mean the path formats shown in this section will be all that is required to use in a widget. However, the Extending Paths for XML Data Access appendix describes XML data access through path extension in full detail.