|
|
News for XML DOM Tutorial |
|
A D V E R T I S E M E N T
1. XML DOM: Adding an Child Element and an attribute using VBScript |
function doInsert() dim objNode, objDOM, strXPath, objParentNode, objChildNode
'//////////////////////////////// '////// Create and display the original XML Document /////// '////////////////////////////////
'Create an XML DOM object from the XML file Set objDOM = CreateObject("Microsoft.XMLDOM") objDOM.async = false objDOM.load("Customers.xml")
'Display the original XML values txtOrig.value = objDOM.xml '//////////////////////////////// '////// Add an attribute to the element where CustomerID = "ANATR" /////// '//////////////////////////////// 'Select the node for which CustomerID = "ANTON" Note that we select attribute values using the "@" 'Define the XPath that references the element where CustomerID = 'ANATR' strXPath = "/customers/customer[@CustomerID='ANATR'~"
'Create a reference to the element for the XPath Query Set objParentNode = CreateObject("Microsoft.XMLDOM") set objParentNode = objDOM.selectSingleNode(strXPath)
'Add an attribute with a name="email" and a value = "markgoldin@attbi.com" AddNodeAttribute objDOM, objParentNode, "email", "YourName@hotmail.com"
'Display the contents of the XML DOM with the New Attribute added txtNew.value = objDOM.xml
'//////////////////////////////// '////// Add a child element to the element modified above (where CustomerID = "ANATR") /////// '//////////////////////////////// 'Create a new element with the name of "abc" AddDomElement objParentNode, "abc", "Value of New Element"
'Display the contents of the XML DOM with the New Attribute added AND the new child element txtNewWithChild.value = objDOM.xml
end function
Sub AddDomElement(objParentNode, strName, strValue) Dim objDOM, objNode Set objDOM = CreateObject("Microsoft.XMLDOM")
Set objNode = objDOM.createElement(strName) objNode.Text = strValue objParentNode.appendChild objNode End Sub
Sub AddNodeAttribute(objDom, objNode, strName, strValue) Dim objAttrib Set objAttrib = objDOM.createAttribute(strName) objAttrib.Text =strValue objNode.Attributes.setNamedItem objAttrib objDOM.documentElement.appendChild objNode End Sub
|
2. How to select specific nodes in XmlDocument() when having a namespace ? |
<%@ import namespace="System.Xml" %> <%@ page language="C#" debug="true"%>
<script runat="server"> void page_load(object sender, System.EventArgs e){
// Create a new XmlDocument object XmlDocument xmlDoc = new XmlDocument(); // Load the xml file into the object xmlDoc.Load(Server.MapPath("XmlDocumentWithSelectNodesAndNamespace.xml")); // Create a namespace manager and pass the NameTable of XmlDocument XmlNamespaceManager nsmRequest = new XmlNamespaceManager(xmlDoc.NameTable); // Add the namespace as in our xml file nsmRequest.AddNamespace("ns", "http://localhost/CategorySchema.xsd");
// Select the nodes with our prefix before each node XmlNode node; node = xmlDoc.SelectSingleNode("/ns:CategoryList/ns:Category/ns:MainCategory[@ID='0'~", nsmRequest);
// Check whether we have found any data if(node != null) { // Printout the value of the node Response.Write(node.InnerXml); } else Response.Write("Sorry no data found!"); } </script>
|
3. How to Load a XML From a String with XmlDocument? |
<%@ import namespace="System.Xml" %> <%@ page language="C#" debug="true"%>
<script runat="server"> void page_load(object sender, System.EventArgs e){
// Create a new XmlDocument object XmlDocument xmlDoc = new XmlDocument(); // Load the xml file into the object
// Our XML in the string string strXML = "<MainCategory>VC++</MainCategory>";
// Load the XML string with the LoadXml function xmlDoc.LoadXml(strXML);
// Print out the value Response.Write(xmlDoc.InnerXml); } </script>
|
4. Hybrid Model Part Two: Choosing between SAX and DOM |
In my last part, I have introduced SAX and DOM parsers with their pros
and cons. I had also introduced user regarding how to choose a parser
depending upon the requirement. But irrespective of types of parser,
the processing overhead of XM document cannot be ruled out. As the
buzzword in humanity, better cure than never cure. So I would rather
suggest how to optimize the XML processing using existing technologies
available in XML technologies. First off, SAX and DOM are standardized
API and they have got widespread adoption. I am not comparing
functionality of SAX and DOM, rather I giving different scenarios,
which can help the User to optimize the XML processing. As I have
already mentioned in Part1 that if you feel that your XML document does
not any manipulation or little manipulation then better go for DOM
parser. And if your XML document needs more manipulation and it is not
well structured the better opt for SAX parser. Here again also I am
suggesting some more points which can help user to enhance the parsing
capability.
Keep following point in your mind when you choose a parser
Use DOM when XML is primary Representation of the Document
Here I should emphasize that if you think that XML is just a data model
and it requires less manipulation, the better use DOM. Because you
don’t need to manipulate the Document and you simply see the document
as a data model.
Let’s take an example of a narrative XML document. So in this case
the document content is the text, and the mark up is simply a
convenient mechanism for augmenting text with some more data. The most
obvious example is the HTML page. The HTML markup tags give document
authors an easy way to influence how their text is presented to the
user. In such cases, the document is really the most convenient
representation of the data. Keep in mind that DOM is more than just a
simple parser; DOM’s generic hierarchical model object model offers
nice, clean solution to precisely these kinds of problems. In DOM,
beside the basic parsing functionality, you have got a generic n-ary
tree implementation, complete with fully functional manipulation
methods allowing you to add, change, or delete nodes in three, navigate
the tree, search the tree, and so forth. In this case, your XML
document is already well structured and you hardly need any
manipulation. So you better opt for DOM parser in this case.
Avoid DOM when You are Only interested in Parts of the Document
Some times in your application you need some part of an XML document.
Let’s take the example of a company’s employee spreadsheet. 10000
9000 10000 In the above case, the XML document might contain lots of
tags with lots of employees. If your application needs to find the
employees with salary more than 10,000$ per month or employees belong
to Austin state then you need to read each employee data and find out
which employee satisfied your criteria. In this case, keeping the whole
document into memory is really the wastage of resources because you
only need a part of XML document which matches your criteria. So in
this case, User has to build a logic to find out the employee which
meets the criteria, in this example employees with salary more than
$10,000. SAX would be best suite for this application, because User
doesn’t need to load the whole document into memory, User doesn’t
need the whole document as an object and there is some manipulation
associated. What required in order to get employees meet this
requirement is to fetch those xml tags which quite matches your
requirement. As SAX is an event based parser so you can track the whole
XML document using event callbacks as pointers. In the above
company’s employee spread, user wants to find out employees with
salary more than or equal to 10,000. Let’s look into ContentHandler
implementstion.
public class ContentHandlerImpl implements ContentHandler { String
currentTag; Vector employeeDetails = new Vector(); HashMap
employeeStore = new HashMap(); String empId;
The currentTag will take care the current tag in XML document, empId is
the employee id. employeeDetails stores only employee first name and
salary. In HashMap employeeStore, I will be storing employee details
vector with key as empId.
The startElement() method’s implementation would be:
public void startElement(String namespaceURI, String localName, String
qName, Attributes atts) throws SAXException { currentTag = qName;
if(qName.equals("employee")){ employeeDetails = new Vector(); int
attrLength = atts.getLength(); empId = atts.getValue("id"); String
firstName = atts.getValue("firstname");
employeeDetails.addElement(firstName); } }
The logic is when, Parser finds an employee tag, it creates a new
Vector to store employee details. Here also I am initializing
currentTag and empId variable. public void endElement(String
namespaceURI, String localName, String qName) throws SAXException {
currentTag = ""; empId = ""; }
In the endElement() method, I am making currentTag is blank and empId
blank.
The main logic of finding employees with salary more than or equal to
10,000, I have put in characters() method. public void
characters(char[] ch, int start, int length) throws SAXException {
if(currentTag.equals("nettake")){ String currSalary = new
String(ch,start,length); currSalary = currSalary.trim(); //This is to
take care any whitespace tag may appear if(currSalary.equals("")){
return; } int iCurrSalary = Integer.parseInt(currSalary); Here parser
checks whether, salary is greater than or equal to 10,000. If it
matches the criteria, then I am putting details in HashMap, otherwise I
am removing the employee from HashMap. if(iCurrSalary>=10000){
employeeDetails.addElement(currSalary); employeeStore.put(empId,
employeeDetails); }else{ employeeStore.remove(empId); } } }
There is an additional method which returns employees meeting the
requirement
public HashMap getEmployeeStore(){ return this.employeeStore; }
This returns HashMap with all employees with salary greater than or
equal to 10,000.
In your MainParser, from where you have instantiated the
ContentHandler, you can get the HashMap
HashMap employeeDetails = myContentHandler.getEmployeeStore();
//myContentHandler is the implementation of ContentHandler interface.
Set keys = employeeDetails.keySet(); Iterator keyIterator =
keys.iterator(); while(keyIterator.hasNext()){ String key =(String)
keyIterator.next(); Vector employee = (Vector)employeeDetails.get(key);
System.out.println(employee); //I am just printing employee vector. }
Note: You can also write a better logic to achieve the same.
The whole idea behind this program is you give emphasize on how your
are extracting a part of your XML document and populating your data
structure ( in this case it is HashMap). You don’t need to load the
whole XML document into memory and you also don’t need navigate all
nodes in XML document as was the case with DOM implementation.
Another thing, I would like to point is, you can achieve the same
functionality using DOM too. As I have already mentioned, if your
document size is very small, then I would rather suggest you to opt for
DOM. But incase of a Company spreadsheet, where there might thousands
of employees and structure of XML Document is very complicated so to
avoid loading the XML document into memory you just need to use your
logic in SAX parser.
In real life, things are rarely so clear-cut, and there will always be
situations where some characteristics of a document suggest that you
use DOM while other suggest you use SAX; for example, when some
documents have a mixture of both narrative and structured data, or
where some of the data maps well onto existing data structures and some
data is well presented by DOM’s hierarchical structure.
In these situations, you can take advantage of DOM being more than just
a
parsing technology. DOM allows you to build up a tree programmatically
as well as through an XML stream, and the fact gives you some
interesting options when dealing with these kind of document
structures; it allows you to take a hybrid approach that draws on the
strengths of both DOM and SAX and avoid many of their respective
weaknesses.
Let’s look again at above example.
|
5. How to create a navigator with XmlDocument and CreateNavigator? |
<%@ import namespace="System.Xml" %> <%@ import namespace="System.Xml.XPath"%> <%@ page language="C#" debug="true"%>
<script runat="server"> void page_load(object sender, System.EventArgs e){
// Create a new XPathDocument object // and pass the filename as a parameter. XPathDocument xpathDoc; xpathDoc = new XPathDocument(Server.MapPath("XmlDocumentWithCreateNavigator.xml"));
// Create a navigator from the XPathDocument XPathNavigator nav = xpathDoc.CreateNavigator(); // Select some nodes XPathNodeIterator nodeIterator = nav.Select("NewsList/News"); // Iterate through the nodes with the iterator while (nodeIterator.MoveNext()) { Response.Write(nodeIterator.Current+"/n"); } } </script>
|
|
Keywords:
News, personality News, News, News questions, character News, knowledge News, personality test, personality News, News are you, News questions and answers.
Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
|
|
HTML Quizzes |
|
XML Quizzes |
|
Browser Scripting Quizzes |
|
Server Scripting Quizzes |
|
.NET (dotnet) Quizzes |
|
Multimedia Quizzes |
|
Web Building Quizzes |
|
Java Quizzes |
|
Programming Langauges Quizzes |
|
Soft Skills Quizzes |
|
Database Quizzes |
|
Operating System Quizzes |
|
Software Testing Quizzes |
|
SAP Module Quizzes |
|
Networking Programming Quizzes |
|
Microsoft Office Quizzes |
|
Accounting Quizzes |
|
|