top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

XML Using Xpath Program

0 votes
337 views

XML and XPath Program: Xpath is called for finding the information within the document.


 


What is XPath?

  1. XPath is a syntax to define the parts of XML document.
  2. XPath uses the path expressions to navigate in XML documents.
  3. XPath contains a library of the standard functions.
  4. XPath is a major element in XSLT.
  5. XPath is also used in XQuery, XPointer and XLink.
  6. XPath is a W3C recommendation. 

Softwares

 

XML copy Editor, XEditor. 

 

Program  

  1. <book>  
  2.     <title>XML</title>  
  3.     <author>Erik T. Ray</author>  
  4.     <year>2003</year>  
  5.     <price>300</price>  
  6. </book>  

Xpath

 

/book 

 

output
 

XML

Erik T. Ray

2003

300

 

Xpath

 

/book/author

 

output

 

Erik T. Ray

posted Jan 12, 2018 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

XML (Extensible Markup Language)

 

You can use prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by  xmlns attribute in the start tag of an element.

The namespace declaration has the following syntax. xmlns:prefix="URI".

 

Name Conflicts in XML

Name conflict is called two tags and has the same name to execute the first tag only. If you write the Namespace control, it conflicts.

This often results in a conflict, when trying to mix XML documents from the different XML Applications.

 

Default Namespace In XML

Defining a default namespace for an element saves us from using the prefixes in all the child elements. In the default namespace, you cannot write the namespace, which automatically used this namespace.

 

(EX: xmlns="namespaceURI")

 

(URI) Uniform Resource Identifier

XML language uses the URL, URI and URN. A Uniform Resource Identifier (URI) is a string of the characters, which identifies an internet resource.

The most common URI is the Uniform Resource Locator (URL), which identifies an internet domain address.

The third not so common type of URI is the Universal Resource Name (URN).

 

Code 

  1. <root xmlns:h="http://www.w3.org/TR/html4/" xmlns:f="http://www.w3schools.com/furniture">  
  2.     <h:table>  
  3.         <h:tr>  
  4.             <h:td>Lion</h:td>  
  5.             <h:td>Tiger</h:td>  
  6.         </h:tr>  
  7.     </h:table>  
  8.     <f:table>  
  9.         <f:name>Box</f:name>  
  10.         <f:width>100</f:width>  
  11.         <f:height>120</f:height>  
  12.     </f:table>  
  13.     <root>  

Output

 

Lion

Tiger

 

Box

100

120 

READ MORE

XPath Expressions

XPath Expressions are statements that can extract useful information from the XPath tree. Instead of just finding nodes, one can count them, add up numeric values, compare strings, and more. They are much like statements in a functional programming language. Every XPath expression evaluates to a single value.

There are four types of expressions in XPath. They are:

  • Node-set: A node-set is an unordered group of nodes from the input document that match an expression’s criteria.
  • Boolean: A Boolean has one of two values: true of false. XSLT allows any kind of data to be transformed into a Boolean. This is often done implicity when a string or a number or a node-set used where a Boolean is expected.
  • Number: XPath numbers are numeric values useful for counting nodes and performing simple arithmetic. The numbers such as 43 or -7000 that look like integers are stored as doubles. Non-number values, such as strings and Booleans, are converted to numbers automatically as necessary.
  • String: A string is a sequence of zero or more Unicode characters. Other data types can be converted to strings using the string() function.

XPath Funcitons

XPath defines various functions required for XPath 2.0, XQuery 1.0 and XSLT 2.0. The different functions and Accessor, AnyURI, Node, Error and Trace, Sequence, Context, Boolean, Duration/Date/Time, String, QName and Numeric.

XML Path Language (XPath) functions can be used to refine XPath queries and enhance the programming power and flexibility of XPath. Each function in the function library is specified using a function prototype that provides the return type, function name, and argument type. If an argument type is followed by a question mark, the argument is optional; otherwise, the argument is required. Function names are case-sensitive.

The default prefix for the function namespace is fn.

READ MORE

Benefits of XPath

XPath is designed for XML documents. It provides a single syntax that you can use for queries, addressing, and patterns. XPath is concise, simple, and powerful.

XPath has many benefits:

  • Syntax is simple for the simple and common cases.
  • Any path that can occur in an XML document and any set of conditions for the nodes in the path can be specified.
  • Any node in an XML document can be uniquely identified.

XPath is designed to be used in many contexts. It is applicable to providing links to nodes, for searching repositories, and for many other applications.

XML Document in XPath

In XPath, an XML document a viewed conceptually as a tree in which each part of the document is represented as a node as shown in figure below:

XPath has seven types of nodes. They are:

  • Root: The XPath tree has a single root node, which contains all other nodes in the tree.
  • Element: Every element in a document has a corresponding element node that appears in the tree under the root node. Within an element node appear all of the other types of nodes that corresponding to the element’s content. Element nodes may have a unique identifier associated with them that is used to reference the node with XPath.
  • Attribute: Each element node has an associated set of attribute nodes, the element is the parent of each of these attribute nodes, however, an attribute node is not a child of its parent element.
  • Text: Character data is grouped into text nodes. Characters inside comments, processing instructions and attribute values do not produce text nodes. The text node has a parent node and it may the child node too.
  • Comment: There is a comment node for every comment, except for any comment that occurs within the documents type declaration. The comment node has a parent node and it may be the child node too.
  • Processing instruction: There is a processing instruction node for every processing instruction, except for any processing instruction that occurs within the document type declaration. The processing instruction node has a parent node and it may be the child node too.
  • Namespace: Each element has an associated set of namespace nodes. Although the namespace node has a parent node, the namespace node is not considered a child of its parent node because they are not contained in a parent node, but are used to provide descriptive information about their parent node.
READ MORE

Introduction to XPath

XPath can be thought of as a query language such as SQL. However, rather than extracting information from a database, it extracts information from an XML document. XPath is a language for retrieving from a database, it extracts information from an XML document. XPath is a language for retrieving information from a XML document. XPath is used to navigate through elements and attributes in an XML document. Thus, XPath allows identifying parts of an XML document.

XPath provides a common syntax as shown in figure:-

 

  • XSLT: XSLT is a language for transforming XML documents into XML, HTML, or text.
  • XQuery: XQuery builds on XPath and is a language for extracting from XML documents.

Benefits of XPath

XPath is desingned for XML documents. It provides a single syntax that you can use for queries, addressing, and patterns. XPath is concise, simple, and powerful.

XPath has many benefits:

  • Syntax is simple for the simple and common cases
  • Any path that can occur in an XML document and any set of conditions for the nodes in the path can be specified.
  • Any node in an XML document can be uniquely identified

XPath is designed to be used in many contexts. It is applicable to providing links to nodes, for searching repositories, and for many other applications.

READ MORE

There are many different techniques to use by which you can create an XML document in C#. One of them is LINQ to XML which we are going to discuss in this article.

Let’s say we need to create an XML as below:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <Parent>  
  3. <Header>  
  4. <FileDetails>  
  5. <FileName>RandomFile</FileName>  
  6. <FileVersion>1.0</FileVersion>  
  7. </FileDetails>  
  8. </Header>  
  9. <Body>  
  10. <Infos>  
  11. <Info Type="Information1">This is Information1</Info>  
  12. <Info Type="Information2">This is Information2</Info>  
  13. </Infos>  
  14. <Users>  
  15. <UserDetails>  
  16. <Name>  
  17. <FirstName>Vipul</FirstName>  
  18.  <MiddleName/>  
  19.                     <LastName>Malhotra</LastName>  
  20.                 </Name>  
  21. <DateOfBirth>12-Apr-1990</DateOfBirth>  
  22. </UserDetails>  
  23. </Users>  
  24. </Body>  

Let’s break the creation of the file in two parts so as to be able to see more features.

We will first create the below Xml:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <Parent>  
  3. <Header>  
  4. <FileDetails>  
  5. <FileName>RandomFile</FileName>  
  6. <FileVersion>1.0</FileVersion>  
  7. </FileDetails>  
  8. </Header>  
  9. <Body>  
  10. <Infos>  
  11. <Info Type="Information1">This is Information1</Info>  
  12. <Info Type="Information2">This is Information2</Info>  
  13. </Infos>  
  14. </Body>  

In order to create this, we will first define an XDocument with the parent root as below:

  1. XDocument doc = new XDocument(new XElement("Parent"));  

After this, we will use this “doc” as the root of the file and will writing nested XElement to it.

Let’s first create the Header portion of the xml.
Header
Please notice that the XElement “Header “ is added as a new element and the further elements are added as nested to this “Header” element. It is due to the reason that the elements are sub-elements of “Header”. Further “FileName” and “FileVersion” element is a sub-element of “FileDetails”

In the same way, we would add another section to the root of the doc. This section would be “Body”. 

The code for the same would be as:
code
This follows the same logic that “Body” is also sub-node of the root “parent” and so it is added directly to the root. Whereas , the element “Infos” is sub-element of “Body” and is so added in the way above. Same goes for “Info” which is a further sub-element of “Infos”. 

Also notice how an attribute is added to each of the “Info” element using XAttribute.

After this, we further need to add the below section as sub-nodes of “Body” and not the root of the application:

  1. <Users>  
  2. <UserDetails>  
  3. <Name>  
  4. <FirstName>Vipul</FirstName>  
  5.  <MiddleName/>  
  6.                     <LastName>Malhotra</LastName>  
  7.                 </Name>  
  8. <DateOfBirth>12-Apr-1990</DateOfBirth>  
  9. </UserDetails>  
  10. </Users>  

In order to do that, we would make sure that the code starts appending the code inside the “Body” tag of the already created xml.

Using XDocument, we can search for the node “Body” and then start adding node XElements to it .
node 
Searching a node Is done using:

Further adding more elements to it is done using the below code:
code
The logic behind the hierarchy is the same as that discussed above.

The code can also be used inside a loop in case we need to add many similar sections to a particular node. Like in this case there can be many users and all of their details would have to be added in different UserDetails section inside the “Body” node.

READ MORE

Introduction

In today's tech world, most of the applications being developed under Logistics, Inventory, Internal Transaction and other domains require day-to-day data in excel files and prefer excel file operations in their applications.

I will be sharing one of the Nuget Package tools which, with very minimal lines of code, will export an excel file for us.

The Tool is Closed XML.

Just write a few lines of code and done! It is developer friendly. If we have used the Open XML, there are a lot of lines of code which are required to export an excel from data. We can create an excel file of 2007/2010 configuration without an Excel application.

To add the closed XML package, we add it directly through the user interface from the Nuget Gallery and also, we can use the Package Manager console to add the package using the below command

PM> Install-Package ClosedXML

Snippet

  1. DataTable dt = new DataTable();  
  2. dt.Columns.AddRange(new DataColumn[3]  
  3. {  
  4.  new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Country", typeof(string))  
  5. });  
  6. dt.Rows.Add(1, "C Sharp corner", "United States");  
  7. dt.Rows.Add(2, "Suraj", "India");  
  8. dt.Rows.Add(3, "Test User", "France");  
  9. dt.Rows.Add(4, "Developer", "Russia"); //Exporting to Excel               
  10. string folderPath = "C:\\Excel\\";              
  11. if (!Directory.Exists(folderPath))              
  12. {                   
  13.     Directory.CreateDirectory(folderPath);            
  14. }     
  15. //Codes for the Closed XML             
  16.     using (XLWorkbook wb = new XLWorkbook())              
  17.     {                
  18.         wb.Worksheets.Add(dt, "Customers");                  
  19.         //wb.SaveAs(folderPath + "DataGridViewExport.xlsx");                
  20.         string myName = Server.UrlEncode("Test" + "_" + DateTime.Now.ToShortDateString() + ".xlsx");        
  21.         MemoryStream stream = GetStream(wb);  
  22.         // The method is defined below             
  23.         Response.Clear();                  
  24.         Response.Buffer = true;              
  25.         Response.AddHeader("content-disposition", "attachment; filename=" + myName);         
  26.         Response.ContentType = "application/vnd.ms-excel";           
  27.         Response.BinaryWrite(stream.ToArray());                
  28.         Response.End();  
  29.     }  

The above code instantiates a data table, with few data initializations.

  1. public MemoryStream GetStream(XLWorkbook excelWorkbook)   
  2. {  
  3.     MemoryStream fs = new MemoryStream();  
  4.     excelWorkbook.SaveAs(fs);  
  5.     fs.Position = 0;  
  6.     return fs;  
  7. }

We are using this method, so as to return a stream in order to download the file in response to using the stream. The save as method of the Closed XML helps create the stream.

Downloaded file looks like below,

file

READ MORE
...