Chilkat HOME ASP Visual Basic VB.NET C# Visual C++ C MFC Delphi FoxPro Java Perl PHP Python Ruby SQL Server VBScript
|
Using Chilkat XML in Ruby: Basic XML Operations Demonstrates much of the basic functionaliy present in the Chilkat XML parser for Ruby scripting.
# file: basicXml.rb
#
# Demonstrates basic XML operations with pigs.xml
require 'chilkat'
# The Chilkat XML parser for Ruby is freeware. The code demonstrated in this
# example can be used in both commercial and non-commercial applications without
# restriction.
# Some Chilkat XML Ruby examples utilize these online XML data samples:
# http://www.chilkatsoft.com/xml-samples/bookstore.xml
# http://www.chilkatsoft.com/xml-samples/nutrition.xml
# http://www.chilkatsoft.com/xml-samples/pigs.xml
# http://www.chilkatsoft.com/xml-samples/plants.xml
# http://www.chilkatsoft.com/xml-samples/japanese.xml
# http://www.chilkatsoft.com/xml-samples/hamlet.xml
# Load pigs.xml
xml = Chilkat::CkXml.new()
xml.LoadXmlFile("pigs.xml")
# Create some temporary string objects we'll use later.
strContent = Chilkat::CkString.new()
strTag = Chilkat::CkString.new()
strXml = Chilkat::CkString.new()
# Print the names of each pig.
# The names are found within each pig's record:
# <pig-rescue>
# <image-base>images</image-base>
# <animal>
# <species>pot belly pig</species>
# <type>Cathy's Herd</type>
# <name>Molly II</name>
# <birth>February, 1998</birth>
# ...
# </animal>
# <animal>
# ...
# </animal>
# Use the SearchForTag method to iterate over <name> nodes
# wherever they may occur in the document. Begin by getting
# the 1st occurance of the tag in the document:
pigName = Chilkat::CkString.new()
nameNode = xml.SearchForTag(nil,"name")
print "Pig Names:\n"
while nameNode != nil
nameNode.get_Content(pigName)
print pigName.getString() + "\n"
# Continue searching beyond where we left off. Notice that the 1st argument
# is not nil.
nameNode = xml.SearchForTag(nameNode,"name")
end
print "------\n"
# Find the pig named Woody
nameNode = xml.SearchForContent(nil,"name","Woody")
# Move up to <animal> node
animalNode = nameNode.GetParent()
# Demonstrate how to use these methods:
# FirstChild
# LastChild
# NextSibling
# PreviousSibling
# get_NumChildren
# GetChild
# GetChildWithTag
# NumChildrenHavingTag
# GetNthChildWithTag
# FindOrAddNewChild
# NewChild
# ExtractChildByName
# ExtractChildByIndex
# RemoveFromTree
# AddChildTree
# RemoveChild
# AppendToContent
# get_Content
# put_Content
# get_Tag
# put_Tag
# GetChildContent
# UpdateChildContent
# ContentMatches
# ChildContentMatches
# HasChildWithTag
# RemoveChildWithContent
# HasChildWithTagAndContent
# HasChildWithContent
# RemoveAllChildren
# RemoveChildByIndex
# AccumulateTagContent
# GetChildContentByIndex
# GetChildTag
# AddToContent
# AddToChildContent
# ----------------------------------------
# FirstChild, LastChild, NextSibling, PreviousSibling
# Iterate of child nodes:
print "Information about Woody:\n"
child = animalNode.FirstChild()
while child != nil
child.get_Content(strContent)
if (strContent.getNumChars() > 0)
child.get_Tag(strTag)
print strTag.getString() + ": " + strContent.getString() + "\n"
end
child = child.NextSibling()
end
print "---------------\n"
# Iterate over the children in reverse order:
print "Information about Woody in reverse order:\n"
child = animalNode.LastChild()
while child != nil
child.get_Content(strContent)
if (strContent.getNumChars() > 0)
child.get_Tag(strTag)
print strTag.getString() + ": " + strContent.getString() + "\n"
end
child = child.PreviousSibling()
end
print "---------------\n"
# ----------------------------------------
# get_NumChildren
# GetChild (by index)
#
# Iterate over the children by index.
print "Information about Woody (by index):\n"
n = animalNode.get_NumChildren()
for i in 0 .. n-1
child = animalNode.GetChild(i)
child.get_Content(strContent)
if (strContent.getNumChars() > 0)
child.get_Tag(strTag)
print strTag.getString() + ": " + strContent.getString() + "\n"
end
end
print "---------------\n"
# ----------------------------------------
# GetChildWithTag - Get a child node by tag
#
child = animalNode.GetChildWithTag("species")
child.get_Content(strContent)
print "Woody's species is: " + strContent.getString() + "\n-------\n"
# ----------------------------------------
# NumChildrenHavingTag
# GetNthChildWithTag
# FindOrAddNewChild
#
# The pigs.xml root node has one <image-base> child, and multiple <animal> children.
# You may iterate over the children with a specific tag by using
# NumChildrenHavingTag/GetNthChildWithTag:
# First, we can always get back to the root node of the document by calling GetRoot:
print "Names of pigs by using NumChildrenHavingTag/GetNthChildWithTag\n"
root = animalNode.GetRoot()
n = root.NumChildrenHavingTag("animal")
for i in 0 .. n-1
animalNode = root.GetNthChildWithTag("animal",i)
animalNode.GetChildContent("name",strContent)
print strContent.getString() + "\n"
end
print "---------------\n"
# ----------------------------------------
# FindOrAddNewChild - Add without duplicating a tag.
# NewChild - Add regardless of duplication.
# NewChild2 - Same as NewChild, but don't return the child node that just got added.
# First, let's get back to Woody's node:
# Find the pig named Woody
nameNode = xml.SearchForContent(nil,"name","Woody")
# Move up to <animal> node
animalNode = nameNode.GetParent()
# Add a new child one having a tag of "weight" does not yet exist.
weightNode = animalNode.FindOrAddNewChild("weight")
# Update the content..
weightNode.put_Content("55")
weightNode.AddAttribute("units","kg")
# A new child may be added with NewChild, which returns the node it creates.
# NewChild will create duplicates, so the following call will create a 2nd "weight" child:
child = animalNode.NewChild("weight","70")
# Call RemoveFromTree to remove a node from the document:
child.RemoveFromTree()
# The NewChild2 method is identical to NewChild, except it does not return the
# child node. This is more efficient if the child node is not needed.
animalNode.NewChild2("color","brown")
# -----------------------------------------------------------------------------
# ExtractChildByName - removes a child tree from the XML document and returns the
# detached child node:
detachedSubTree = animalNode.ExtractChildByName("color",nil,nil)
# ExtractChildByName allows for an attribute name/value to be specified.
# If so, the first child matching all non-nil values is extracted:
detachedSubTree = animalNode.ExtractChildByName("weight","units","kg")
# -----------------------------------------------------------------------------
# ExtractChildByIndex - same as ExtractChildByName, except the child tree is removed by index.
# The following line extracts the 1st child (and all descendants).
detachedSubTree = animalNode.ExtractChildByIndex(0)
# -----------------------------------------------------------------------------
# A complete tree can be added as a child by calling AddChildTree
# This line adds back what was previously removed:
animalNode.AddChildTree(detachedSubTree)
# -----------------------------------------------------------------------------
# RemoveFromTree - detacheds the caller from the XML document.
# A comment: The get_TreeId returns a unique id that identifies the XML document
# an XML node belongs to. If two nodes have different Tree IDs, they belong to
# different XML documents. Let's examine the Tree IDs before and after the call
# to RemoveFromTree:
root = animalNode.GetRoot()
rootTreeId = root.get_TreeId()
animTreeId = animalNode.get_TreeId()
printf "1) Root Tree ID = %d, animalNode Tree ID = %d\n",rootTreeId,animTreeId
# Now remove animalNode from the tree and re-examine the IDs:
animalNode.RemoveFromTree()
rootTreeId = root.get_TreeId()
animTreeId = animalNode.get_TreeId()
printf "2) Root Tree ID = %d, animalNode Tree ID = %d\n",rootTreeId,animTreeId
# Now re-add animalNode back to the original tree, and re-examine the Tree IDs:
root.AddChildTree(animalNode)
rootTreeId = root.get_TreeId()
animTreeId = animalNode.get_TreeId()
printf "3) Root Tree ID = %d, animalNode Tree ID = %d\n",rootTreeId,animTreeId
# -----------------------------------------------------------------------------
# The RemoveChild method discards all child nodes having a specific tag.
# For example, we could remove all "animal" child nodes from the root.
root.RemoveChild("animal")
# -----------------------------------------------------------------------------
# Given that we've trashed our XML document with RemoveChild, let's re-load
# it from the file...
# LoadXmlFile causes the calling object's existing XML document to be
# replaced with the contents of the file.
root.LoadXmlFile("pigs.xml")
# Get back to Woody's node:
# Find the pig named Woody
nameNode = root.SearchForContent(nil,"name","Woody")
# Move up to <animal> node
animalNode = nameNode.GetParent()
# The AppendToContent method appends text to a node's existing content:
infoNode = animalNode.FindChild("info")
infoNode.AppendToContent(" Woody likes to eat corn.")
infoNode.get_Content(strContent)
printf "----\nNew Content: %s\n",strContent.getString()
# -----------------------------------------------------------------------------
# The get_Content/put_Content and get_Tag/put_Tag methods can update/get the
# content and tag of any node:
speciesNode = animalNode.FindChild("species")
speciesNode.GetXml(strXml)
# prints: <species>pot belly pig</species>
printf "----\n%s\n",strXml.getString()
speciesNode.put_Tag("breed")
speciesNode.GetXml(strXml)
# prints: <breed>pot belly pig</breed>
printf "----\n%s\n",strXml.getString()
speciesNode.put_Content("red wattle")
speciesNode.GetXml(strXml)
# prints: <breed>red wattle</breed>
printf "----\n%s\n",strXml.getString()
speciesNode.get_Tag(strTag)
speciesNode.get_Content(strContent)
# prints: breed: red wattle
printf "----\n%s: %s\n",strTag.getString(),strContent.getString()
# Restore the original speciesNode:
speciesNode.put_Tag("species")
speciesNode.put_Content("pot belly pig")
# -----------------------------------------------------------------------------
# Method exist for working with child nodes without having to instantiate
# an XML object for each child:
# GetChildContent
# UpdateChildContent
# ChildContentMatches
# HasChildWithTag
# RemoveChildWithContent
# HasChildWithTagAndContent
# HasChildWithContent
# AddToChildContent
# AddToContent
#
# In this example, our animalNode looks like this:
# <animal>
# <species>pot belly pig</species>
# <type>Barnyard</type>
# <name>Woody</name>
# <birth>1996</birth>
# <in-date>September, 2004</in-date>
# <from>Owner Relinquish</from>
# <sponsor>Guy</sponsor>
# <gender spay-neuter="yes">M</gender>
# ...
# GetChildContent
animalNode.GetChildContent("type",strContent)
# prints "Barnyard"
printf "----\n%s\n",strContent.getString()
# UpdateChildContent
animalNode.UpdateChildContent("type","Wild")
animalNode.GetChildContent("type",strContent)
# prints "Wild"
printf "----\n%s\n",strContent.getString()
# ChildContentMatches
caseSensitive = false
if animalNode.ChildContentMatches("species","*belly*",caseSensitive)
print "species matches *belly*\n"
else
print "species does not match *belly*\n"
end
# HasChildWithTag
if animalNode.HasChildWithTag("birth")
print "has birth XML child!\n"
else
print "does not have birth XML child!"
end
# RemoveChildWithContent - Removes all children having the exact content specified.
animalNode.RemoveChildWithContent("Owner Relinquish")
# HasChildWithTagAndContent - returns true if a child exist with the exact tag AND content
if animalNode.HasChildWithTagAndContent("species","pot belly pig")
print "This is a pot belly pig!\n"
else
print "This is NOT a pot belly pig!\n"
end
# HasChildWithContent - Returns true if one of the children has the exact content,
# regardless of the child's tag.
if animalNode.HasChildWithContent("M")
print "This is a male pig!\n"
else
print "This is NOT a male pig!\n"
end
# AddToChildContent - If a child's content is an integer, this method adds an amount
# to it.
# Add 1 to the birth year:
animalNode.AddToChildContent("birth",1)
animalNode.GetChildContent("birth",strContent)
# Prints 1997
printf "----\n%s\n",strContent.getString()
# -----------------------------------------------------------------------------
# Some methods provide the ability to work with children by index:
# GetChildTag
# GetChildContentByIndex
n = animalNode.get_NumChildren()
print "----\n"
for i in 0 .. n-1
animalNode.GetChildTag(i,strTag)
animalNode.GetChildContentByIndex(i,strContent)
printf "%d: %s: %s\n",i,strTag.getString(),strContent.getString()
end
# RemoveChildByIndex - Discards the Nth child from the XML document
animalNode.RemoveChildByIndex(4)
# -----------------------------------------------------------------------------
# A few other misc methods:
# AddToContent - If the content is an integer, adds an integer amount to it:
birthNode = animalNode.FindChild("birth")
birthNode.AddToContent(-1)
birthNode.get_Content(strContent)
# Prints 1996
printf "----\n%s\n",strContent.getString()
# ContentMatches - use an asterisk to match 0 or more of any character
caseSensitive = false
if birthNode.ContentMatches("199*",caseSensitive)
printf "----\nBirth is before year 2000!\n"
end
# AccumulateTagContent - accumulates the content of all nodes having a specific tag
# and returns a string with the accmulated content:
skipTags = ""
# The skipTags tells the method to NOT descend down sub-trees having any
# of the listed tags. For example, one might set skipTags = "picture|medical".
# Tags in skipTags are separated by vertical bar characters.
root.AccumulateTagContent("info",skipTags,strContent)
strContent.replaceAllOccurances("\n"," ")
# trimInsideSpaces prevents no more than one consecutive SPACE character in a row
# from occuring.
strContent.trimInsideSpaces()
printf "----\n%s\n",strContent.getString()
|
Need a specific example? Send a request to support@chilkatsoft.com
© 2000-2008 Chilkat Software, Inc. All Rights Reserved.