Home > Articles

This chapter is from the book

This chapter is from the book

Creating New Content

At this point we've read and modified simple information such as attributes and text nodes. Modifying the content of an element is a bit more complex, and requires adding or removing nodes.

In this section, we'll start by creating a new person element, giving it an attribute, and adding it to the persons element for each activity. We'll then create a new document and populate it with the participant information for each activity.

Finally, we'll look at some of the ways that current implementations persist (save) a Document object.

Creating an Element

Before you can add an element to a document, you must first create it. Creating elements and other nodes is the responsibility of the Document object.

In Listing 3.17, we'll create a method for adding the new person, and execute it before displaying the activity information so the number of available spaces is correct.

Listing 3.17 Creating an Element

...
   NodeList activitiesList =
         activitiesElement.getElementsByTagName("activity");
   for (int i=0; i < activitiesList.getLength(); i++) {

     Node thisNode = activitiesList.item(i);
     addNewParticipant(thisNode, "P4");
     displayActivity(thisNode);
   }
  }
...
  public static void addNewParticipant(Node thisAct, String thisPerson) {

   Element thisActElement = (Element)thisAct;

   Node thisPersons = thisActElement.getElementsByTagName("persons").item(0);
   Element thisPersonsElement = (Element)thisPersons;

   Document doc = thisPersonsElement.getOwnerDocument();

   Element thisPersonElement = doc.createElement("person");
   thisPersonElement.setAttribute("personid", thisPerson);
  }
}

First, we establish the parent node for the new child node. In this case, that's the persons element within each activity element. Next, we need to create the actual element node, which means that we need the Document object. As before, we need to get a reference from the element itself because we're out of the original Document object's scope.

The Document creates the element (and we assign it a personid attribute) but at this moment, the element is in limbo. It's not yet a part of the tree.

Adding the Element

To make a newly created element part of the tree, we have to add it to the structure. There are several ways to do this. The first, and most common, is to simply append it to the content of the parent element, as shown in Listing 3.18.

Listing 3.18 Appending a Child

...
  public static void addNewParticipant(Node thisAct, String thisPerson) {

   Element thisActElement = (Element)thisAct;

   Node thisPersons = thisActElement.getElementsByTagName("persons").item(0);
   Element thisPersonsElement = (Element)thisPersons;

   Document doc = thisPersonsElement.getOwnerDocument();
   Element thisPersonElement = doc.createElement("person");
   thisPersonElement.setAttribute("personid", thisPerson);

   thisPersonsElement.appendChild(thisPersonElement);
  }
}

In this case, we simply add the new element to the content that already exists. Before, the persons element may have looked like the following:

      <persons>
        <person personid="P2"/>
        <person personid="P1"/>
      </persons>

Now it looks like this:

      <persons>
        <person personid="P2"/>
        <person personid="P1"/>
        <person personid="P4"/>
      </persons>

The Node interface also provides two other construction-type methods.

The first, insertBefore(), takes two arguments: the node being added, and the node that it's to precede. So if P1Element represents the person with a personid of P1, the statement

   thisPersonsElement.insertBefore(thisPersonElement, P1Element);

results in a structure of

      <persons>
        <person personid="P2"/>
        <person personid="P4"/>
        <person personid="P1"/>
      </persons>

Note that a node may only appear in a Document once, so if thisPersonElement already exists somewhere else, it's automatically removed, and then placed in its new position.

The second additional method is replaceChild(), where a call to

  Element replacedChild =
        thisPersonsElement.replaceChild(thisPersonElement, P1Element);

results in a structure of

      <persons>
        <person personid="P2"/>
        <person personid="P4"/>
      </persons>

In this case, replacedChild is also equal to P1Element, as replaceChild() returns the node that was replaced.

Creating a New Document

Now we're ready to create a new document. Overall, there's just one new technique: actually creating the document. Again, this is not the standard way of doing things; in the case of the Java implementation, the DocumentBuilder creates a new Document object.

The rest of Listing 3.19 simply shows another use for the techniques we covered earlier in this chapter.

Listing 3.19 Creating the New Document

...
public class ActivityListing {

  public static void println(String arg) {
   System.out.println(arg);
  }

  public static void main (String args[]) {
   File docFile = new File("activities.xml");
   Document doc = null;
   Document newDoc = null;

   try {

     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();
     doc = db.parse(docFile);

     newDoc = db.newDocument();

   } catch (Exception e) {
     System.out.println("Problem parsing the file.");
   }

   Element newRoot = newDoc.createElement("roster");
   newDoc.appendChild(newRoot);

   Element root = doc.getDocumentElement();

   Node firstChild = root.getFirstChild();
   Node secondChild = firstChild.getNextSibling();

   Element activitiesElement = (Element)secondChild;
   NodeList activitiesList =
         activitiesElement.getElementsByTagName("activity");
   for (int i=0; i < activitiesList.getLength(); i++) {

     Node thisNode = activitiesList.item(i);
     addNewParticipant(thisNode, "P4");
     displayActivity(thisNode);

     Element thisActivity = (Element)thisNode;
     String thisActivityId = thisActivity.getAttribute("activityid");

     Element newActivity = newDoc.createElement("activity");
     newActivity.setAttribute("activityid", thisActivityId);

     Element personsElement =
        (Element)thisActivity.getElementsByTagName("persons").item(0);
     NodeList participants = personsElement.getElementsByTagName("person");

     for (int j=0; j < participants.getLength(); j++) {
       Element thisPerson = (Element)participants.item(j);
       String thisPersonId = thisPerson.getAttribute("personid");

       Element thisNewPerson = newDoc.createElement("person");
       Node thisPersonText = newDoc.createTextNode(thisPersonId);
       thisNewPerson.appendChild(thisPersonText);

       newActivity.appendChild(thisNewPerson);
     }

     newRoot.appendChild(newActivity);

   }
  }
...

(If you're working in one of the other languages, stay with me for a moment. We'll cover the creation of a document in the next section.)

A document isn't well-formed XML until it has a root element, so next we create a new Element node with the name roster and append it to the document itself.

Now we're ready to start adding new nodes to the document. We simply pull information from the old document just as we did before, then add it to the new document. For example, we retrieve the activityid using the getAttribute() method, then create a new element and add the attribute to it.

The person elements are a bit different, because we're changing the personid from an attribute to the text of the element. Because of this, creating the new person element involves creating a new text node, then appending it as a child to the element. As each person element is completed, append it to the activity.

Finally, append each activity to the new root element.

Which Document?

When creating new elements, be sure that you use the right document to do it. Nodes are not easily transferable between documents, so create the node using the document that will ultimately contain it.

Saving the Document

The DOM Level 2.0 doesn't specify a means for saving an XML document (though that's planned for Level 3.0), so it's up to the implementation to decide how to do so. The following subsections provide some examples.

Java

The JAXP specification doesn't include a standard way to save documents, but it's recommended that you use the package's XSL transformation abilities. We'll cover transformation in detail in Chapter 10, "Transformations Within an Application." For now, understand that we're transforming a document, but we're not providing a style sheet, so the document comes through unchanged. Listing 3.20a demonstrates the process.

Listing 3.20a Saving the Document

...
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class ActivityListing {
...
  public static void main (String args[]) {
...
     newRoot.appendChild(newActivity);

   }

   try {

     TransformerFactory transformerFactory =
             TransformerFactory.newInstance();
     Transformer transformer =
            transformerFactory.newTransformer();

     DOMSource origDocSource = new DOMSource(doc);
     StreamResult origResult = new StreamResult("updated.xml");
     transformer.transform(origDocSource, origResult);

     DOMSource newDocSource = new DOMSource(newDoc);
     StreamResult newResult = new StreamResult("roster.xml");
     transformer.transform(newDocSource, newResult);

   } catch (Exception e) {
     println("Could not save document.");
   }
  }

  public static void displayActivity(Node thisAct) {
...

When transforming documents, a Transformer takes the source and sends it to the result after applying the instructions specified by the style sheet with which the Transformer was created. Because there is no style sheet in this case, the Transformer makes no changes and simply sends the original document to the result, which in this case is a file.

C++

In C++, creating an XML document is as simple as calling the save function with the destination filename.

Listing 3.20b Saving the Document in C++

#include "stdafx.h"
#import "C:\windows\system32\msxml2.dll"
using namespace MSXML2;

int _tmain(int argc, _TCHAR* argv[])
{
  ::CoInitialize(NULL);
  try
  {
    HRESULT hr;
    CComPtr<MSXML2::IXMLDOMDocument> pDomDocument;

    // We create the initial empty DOMDocument
    hr = pDomDocument.CoCreateInstance(__uuidof(MSXML2::DOMDocument));

    // We load the XML file into the DOMDocument
    hr = pDomDocument->load("activities.xml");

    // Here we can place code that makes modifications to the DOMDocument

    // Now, we save the DOMDocument as some other XML file
    hr = pDomDocument->save("new_activities.xml");
  }

  catch(...)
  {
    wprintf(L"Caught the exception");
  }
  ::CoUninitialize();
  return 0;
}

Visual Basic

The VB process is as simple as in VC++, as Listing 3.20c shows.

Listing 3.20c Saving the Document in VB

  Private Sub Button1_Click(ByVal sender As System.Object,
               ByVal e As System.EventArgs) _
               Handles Button1.Click

    'We create the initial empty DOMDocument
    Dim xmldoc As New MSXML2.DOMDocument40()
    Dim hr As Boolean

    'We load the XML file into the DOMDocument
    xmldoc.async = False
    hr = xmldoc.load("activities.xml")

    'Here we can place code that makes modifications to the DOMDocument

    'Now, we save the DOMDocument as some other XML file
    xmldoc.save("new_activities.xml")
  End Sub

PHP

Creating a new document and writing DOM structures to disk are both easy using PHP, but at the time of this writing the current version of PHP, 4.2.1, has two bugs to watch out for. First, formatting the output removes whitespace nodes, and second, the PHP version of getElementById(), get_element_by_id(), doesn't actually search for an element with an attribute of type ID. Instead, it searches for an element named ID. This behavior will likely be fixed in future versions, but I've included a workaround as part of Listing 3.20d.

Output Formatting and Apache

If you're running PHP version 4.2.2 or earlier as an Apache module, beware of letting dump_file() or dump_mem() format your XML output; the formatting changes (such as removing whitespace nodes) persist across requests, even if you load the source XML document again.

Listing 3.20d Saving the Document in PHP

<?php

...

$new_doc = domxml_new_doc('1.0');
$new_root = $new_doc->create_element('roster');

$first_child   =& $root->first_child();
$activities_el  =& $first_child->next_sibling();
$activities_list = $activities_el->get_elements_by_tagname("activity");
$count_activities = count($activities_list);

for ($i = 0; $i < $count_activities; $i++) {
 $act =& $activities_list[$i];
 add_new_participant($act,"P4");
 display_activity($act);

 $act_id = $act->get_attribute("activityid");
 $new_act = $new_doc->create_element("activity");
 $new_act->set_attribute("activityid",$act_id);

 $persons_el_list = $act->get_elements_by_tagname("persons");
 $persons_el   =& $persons_el_list[0];
 $person_list   = $persons_el->get_elements_by_tagname("person") ;
 $count_persons  = count($person_list);
 for ($j = 0; $j < $count_persons; $j++) {
  $person     = $person_list[$j];
  $person_id    = $person->get_attribute("personid");
  $new_person   = $new_doc->create_element("person");
  $new_person_text = $new_doc->create_text_node($person_id);
  $new_person->append_child($new_person_text);
  $new_act->append_child($new_person);
 }

 $new_root->append_child($new_act);
}

$new_doc->append_child($new_root);

$doc->dump_file("updated.xml",false,false);
$new_doc->dump_file("roster.xml",false,false);

...

function add_new_participant (&$act, $person)
{
 $act_persons_list = $act->get_elements_by_tagname("persons");
 $act_persons_el  =& $act_persons_list[0];

 $doc      =& $act_persons_el->owner_document();
 $new_person_el = $doc->create_element("person");
 $new_person_el->set_attribute("personid",$person);
 $act_persons_el->append_child($new_person_el);
}

function & get_element_by_id(&$doc, $tagname, $attr_name, $value)
{
 $tags    = $doc->get_elements_by_tagname($tagname);
 $count_tags = count($tags);

 for ($i = 0; $i < $count_tags; $i++) {
  $el =& $tags[$i];
  if ($el->get_attribute($attr_name) == $value) {
   return $el;
  }
 }

 return false;
}
?>

Perl

Creating a Document object in Perl is a bit more complex than it is in Java. Instead of using a document builder or factory object, with XML::Xerces you use the DOMImplementation object to create a new, empty document type based on a DTD. (The DTD document doesn't have to exist, but you do have to put a DTD name in the command.) Then you can create an instance of that DocumentType, get the root Document object, and add elements.

On the other hand, saving the file is much easier. Instead of using an XSLT transform, just open a FileHandle for writing, format the document, and print it to the open FileHandle (see Listing 3.20e).

Listing 3.20e Saving the Document in Perl

use FileHandle;
use XML::Xerces;
use XML::Xerces::DOMParse;

my $file  = XML::Xerces::LocalFileInputSource->new("activities.xml");
my $parser = XML::Xerces::DOMParser->new();
eval { $parser->parse($file); };
XML::Xerces::error($@) if $@;

my $doc = $parser->getDocument();
my $root = $doc->getDocumentElement();

my $first_child  = $root->getFirstChild();
my $activities_el = $first_child->getNextSibling();

my $impl   = XML::Xerces::DOM_DOMImplementation::getImplementation();
my $new_dt  = $impl->createDocumentType( 'roster', '', 'roster.dtd' );
my $new_doc = $impl->createDocument( 'roster', 'roster', $new_dt );
my $new_root = $new_doc->getDocumentElement();
for my $act ( $activities_el->getElementsByTagName("activity") ) {
  add_new_participant( $act, "P4" );
  display_activity($act);

  ...

}

my $updated = new FileHandle( "updated.xml", "w" );
$XML::Xerces::DOMParse::INDENT = " ";
XML::Xerces::DOMParse::format($doc);
XML::Xerces::DOMParse::print( $updated, $doc );
$updated->close;

my $roster = new FileHandle( "roster.xml", "w" );
$XML::Xerces::DOMParse::INDENT = " ";
XML::Xerces::DOMParse::format($new_doc);
XML::Xerces::DOMParse::print( $roster, $new_doc );
$roster->close;
...

sub add_new_participant {
  my $act  = shift;
  my $person = shift;

  my $act_persons_el = $act->getElementsByTagName("persons")->item(0);

  my $doc      = $act_persons_el->getOwnerDocument();
  my $new_person_el = $doc->createElement("person");
  $new_person_el->setAttribute( "personid", $person );
  $act_persons_el->appendChild($new_person_el);
}

The Result

The result of all the work we've done in this chapter is an XML document with activity and person elements, as shown in Listing 3.21. (I've added whitespace to make the document a bit more readable.)

Listing 3.21 The Resulting Document

<?xml version="1.0" encoding="UTF-8"?>
<roster>
  <activity activityid="A1">
   <person>P2</person>
   <person>P1</person>
   <person>P4</person>
  </activity>
  <activity activityid="A2">
   <person>P4</person>
  </activity>
</roster>

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020