using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.Load("booksort.xml"); //Select the book node with the matching attribute value. XmlNode nodeToFind; XmlElement root = doc.DocumentElement; // Selects all the title elements that have an attribute named lang nodeToFind = root.SelectSingleNode("//title[@lang]"); if( nodeToFind != null ) { // It was found, manipulate it. } else { // It was not found. } } } |
Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts
Wednesday, 13 June 2012
check if node exists
Friday, 17 February 2012
C# - Select XML Nodes by Name
To find nodes in an XML file you can use XPath expressions. Method XmlNode.SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.SelectSingleNode finds the first node that matches the XPath string.
Suppose we have this XML file.
[XML]
To get all <Name> nodes use XPath expression
[C#]
The output is:
Suppose we have this XML file.
[XML]
<Names>
<Name>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Name>
<Name>
<FirstName>James</FirstName>
<LastName>White</LastName>
</Name>
</Names>
To get all <Name> nodes use XPath expression
/Names/Name. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply index XmlNode with the node name: xmlNode["FirstName"].InnerText. See the example below.[C#]
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"
XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
string firstName = xn["FirstName"].InnerText;
string lastName = xn["LastName"].InnerText;
Console.WriteLine("Name: {0} {1}", firstName, lastName);
}
The output is:
Name: John Smith
Name: James White
Monday, 19 December 2011
Select XML Nodes by Name in C#
To find nodes in an XML file you can use XPath expressions. Method XmlNode.SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.SelectSingleNode finds the first node that matches the XPath string.
Suppose we have this XML file.
[XML]
To get all <Name> nodes use XPath expression
[C#]
The output is:
Suppose we have this XML file.
[XML]
<Names>
<Name>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Name>
<Name>
<FirstName>James</FirstName>
<LastName>White</LastName>
</Name>
</Names>
To get all <Name> nodes use XPath expression
/Names/Name. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply index XmlNode with the node name: xmlNode["FirstName"].InnerText. See the example below.[C#]
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"
XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
string firstName = xn["FirstName"].InnerText;
string lastName = xn["LastName"].InnerText;
Console.WriteLine("Name: {0} {1}", firstName, lastName);
}
The output is:
Name: John Smith
Name: James White
Friday, 16 December 2011
How to read XML from a file by using Visual C#
This article describes how to use the XmlTextReader class to read Extensible Markup Language (XML) from a file. XmlTextReaderprovides direct parsing and tokenizing of XML and implements the XML 1.0 specification as well as the namespaces in the XML specification from the World Wide Web Consortium (W3C). This article provides fast, tokenized stream access to XML rather than using an object model such as the XML Document Object Model (DOM).
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
This article assumes that you are familiar with the following topics:
This example uses a file named Books.xml. You can create your own Books.xml file or use the sample file that is included with the .NET Software Development Kit (SDK) QuickStarts in the following folder:
You must copy Books.xml to the \Bin\Debug folder, which is located under the folder in which you create this project. Books.xml is also available for download.
When you test the code, you may receive the following exception error message: Unhandled Exception: System.Xml.XmlException: Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it.
Additional information: System error. The exception error occurs on the following line of code: While
The exception error is caused by an invalid processing instruction. For example, the processing instruction may contain extraneous spaces. The following is an example of an invalid processing instruction:
This xml tag has a space preceding the ‘<’ bracket. Remove the preceding whitespace to resolve the error.
Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
- Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET
This article assumes that you are familiar with the following topics:
- XML terminology
- Creating and reading an XML file
How to read XML from a file
This example uses a file named Books.xml. You can create your own Books.xml file or use the sample file that is included with the .NET Software Development Kit (SDK) QuickStarts in the following folder:
\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Samples\QuickStart\Howto\Samples\Xml\Transformxml\Cs
You must copy Books.xml to the \Bin\Debug folder, which is located under the folder in which you create this project. Books.xml is also available for download.
- Start Visual Studio 2005 or Visual Studio .NET.
- Create a new Visual C# Console Application. continue through these steps to build the application.
- Make sure that the project contains a reference to the System.Xml.dll assembly.
- Specify the using directive on the System.Xml namespace so that you are not required to qualify XmlTextReader declarations later in your code. You must use the usingdirective before any other declarations.
using System.Xml;
- Create an instance of an XmlTextReader object, and populate it with the XML file. Typically, the XmlTextReader class is used if you need to access the XML as raw data without the overhead of a DOM; thus, the XmlTextReader class provides a faster mechanism for reading XML. The XmlTextReader class has different constructors to specify the location of the XML data. The following code creates an instance of the XmlTextReaderclass and loads the Books.xml file. Add the following code to the Main procedure of Class1.
XmlTextReader reader = new XmlTextReader ("books.xml"); - Read through the XML. (Note that this step demonstrates an outer "while" loop, and the next two steps demonstrate how to use that loop to read the XML.) After you create the XmlTextReader object, use the Read method to read the XML data. The Read method continues to move through the XML file sequentially until it reaches the end of the file, at which point the Readmethod returns a value of "False."
while (reader.Read())
{
// Do some work here on the data.
Console.WriteLine(reader.Name);
}
Console.ReadLine(); - Inspect the nodes. To process the XML data, each record has a node type that can be determined from the NodeType property. The Name and Value properties return the node name (the element and attribute names) and the node value (the node text) of the current node (or record). The NodeTypeenumeration determines the node type. The following sample code displays the name of the elements and the document type. Note that this sample ignores element attributes.
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType. EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
} - Inspect the attributes. Element node types can include a list of attribute nodes that are associated with them. The MovetoNextAttribute method moves sequentially through each attribute in the element. Use the HasAttributes property to test whether the node has any attributes. The AttributeCountproperty returns the number of attributes for the current node.
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
while (reader.MoveToNextAttribute()) // Read the attributes.
Console.Write(" " + reader.Name + "='" + reader.Value + "'");
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType. EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
} - Save and close your project.
Complete code listing
using System;
using System.Xml;
namespace ReadXMLfromFile
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
XmlTextReader reader = new XmlTextReader ("books.xml");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
Console.ReadLine();
}
}
}
Sample output
<bookstore>
<book>
<title>
The Autobiography of Benjamin Franklin
</title>
<author>
<first-name>
Benjamin
</first-name>
<last-name>
Franklin
</last-name>
</author>
<price>
8.99
</price>
</book>
<book>
<title>
The Confidence Man
</title>
<author>
<first-name>
Herman
</first-name>
<last-name>
Melville
</last-name>
</author>
<price>
11.99
</price>
</book>
<book>
<title>
The Gorgias
</title>
<author>
<name>
Plato
</name>
</author>
<price>
9.99
</price>
</book>
</bookstore>
Troubleshooting
When you test the code, you may receive the following exception error message: Unhandled Exception: System.Xml.XmlException: Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it.
Additional information: System error. The exception error occurs on the following line of code: While
(reader.Read())
The exception error is caused by an invalid processing instruction. For example, the processing instruction may contain extraneous spaces. The following is an example of an invalid processing instruction:
<?xml version='1.0' ?>
This xml tag has a space preceding the ‘<’ bracket. Remove the preceding whitespace to resolve the error.
XmlReader to read an XML File and Document Element
XML
C#
}
<?xml version="1.0" encoding="utf-8"?>
<NewsLetters Root="True">
<EMail Date="10/10/2009">hello@hello.com</EMail>
<EMail Date="10/10/2009">hello@hello.com</EMail>
<EMail Date="10/10/2009">hello@hello.com</EMail>
<EMail Date="10/10/2009">hello@hello.com</EMail>
</NewsLetters>
C#
public static string TotalMemberCount()
{
int totalCount = 0;
using (XmlTextReader reader = new XmlTextReader(HttpContext.Current.Server.MapPath("~/Newsletter/NewsLetter.xml")))
{
while (reader.Read())
{
if (reader.NodeType != XmlNodeType.XmlDeclaration && reader.NodeType == XmlNodeType.Element)
{
if (reader.MoveToFirstAttribute())
{
if (reader.Value == "True")
//gotcha, I don't want this,this is root element
continue;
}
totalCount++;
}
}
return totalCount.ToString();
}}
Difference between XmlNodeType.Element and XmlNodeType.Document
What's XmlNodeType.Document ?
Difference between XmlNodeType.Element and XmlNodeType.Document?
Difference between XmlNodeType.Element and XmlNodeType.Document?
- It's certainly not a "generic solution", since your code is now completely dependent on information in the XML - your method can only count elements properly if the XML document it's processing contains the flag attribute that you've added.
- The flag attribute's unnecessary. Any time an
XmlReaderstarts at the beginning of the stream it's reading, the first element it reads is always going to be the top-level element. It can't possibly be anything else. Instead of adding an attribute to your document to identify the top-level element, you can just use a flag to track whether or not you've read the top-level element yet. Or heck, you can just subtract 1 from the total. - And even if you did need the flag attribute, you're doing it wrong. You're using
MoveToFirstAttributeto find it. What if there's more than one atttribute on the element? What if the first attribute your code finds whose value isTrueisn'tRoot? And what if one of the child elements has an attribute on it with that value? If you're going to use an attribute for this purpose, you should, at the very least, search for it by name. - This code won't count all child elements of the top-level element, it will count all descendant elements. The reader moves from node to node in document order. If an element node has a child node, that child node is the next node that gets read by
Read(). There are methods of theXmlReaderthat you can use to read an entire element and all of its content in one single gulp, but you're not using them. - The condition
reader.NodeType != XmlNodeType.XmlDeclaration && reader.NodeType == XmlNodeType.Elementis redundant: there's no way that a node can be an XML declaration if it's an element.
Convert Xml document to String
Default.aspx :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="Literal1" runat="server" Mode="Encode"></asp:Literal></div>
</form>
</body>
</html>
Default.aspx.cs :
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<deneme/>");
#region just to remind myself something
XmlNode node = doc.CreateElement("serkan");
doc.DocumentElement.AppendChild(node);
#endregion
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
doc.WriteTo(tx);
// i use literal control because when you set its mode to "encode", you can write xml tags to browser window as they are
Literal1.Text = sw.ToString();
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="Literal1" runat="server" Mode="Encode"></asp:Literal></div>
</form>
</body>
</html>
Default.aspx.cs :
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<deneme/>");
#region just to remind myself something
XmlNode node = doc.CreateElement("serkan");
doc.DocumentElement.AppendChild(node);
#endregion
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
doc.WriteTo(tx);
// i use literal control because when you set its mode to "encode", you can write xml tags to browser window as they are
Literal1.Text = sw.ToString();
}
}
Different ways how to escape an XML string in C#
Different ways how to escape an XML string in C#
XML encoding is necessary if you have to save XML text in an XML document. If you don't escape special chars the XML to insert will become a part of the original XML DOM and not a value of a node.
Escaping the XML means basically replacing 5 chars with new values.
These replacements are:
| < | -> | < |
| > | -> | > |
| " | -> | " |
| ' | -> | ' |
| & | -> | & |
Here are 4 ways you can encode XML in C#
1. string.Replace() 5 times
This is ugly but it works. Note that Replace("&", "&") has to be the first replace so we don't replace other already escaped &.
string xml = "<node>it's my \"node\" & i like it<node>";
encodedXml = xml.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """).Replace("'", "'");
// RESULT: <node>it's my "node" & i like it<node>
2. System.Web.HttpUtility.HtmlEncode()
Used for encoding HTML, but HTML is a form of XML so we can use that too. Mostly used in ASP.NET apps. Note that HtmlEncode does NOT encode apostrophes ( ' ).
string xml = "<node>it's my \"node\" & i like it<node>";
string encodedXml = HttpUtility.HtmlEncode(xml);
// RESULT: <node>it's my "node" & i like it<node>
3. System.Security.SecurityElement.Escape()
In Windows Forms or Console apps I use this method. If nothing else it saves me including the System.Web reference in my projects and it encodes all 5 char.
string xml = "<node>it's my \"node\" & i like it<node>";
string encodedXml = System.Security.SecurityElement.Escape(xml);
// RESULT: <node>it's my "node" & i like it<node>
4. System.Xml.XmlTextWriter
Using XmlTextWriter you don't have to worry about escaping anything since it escapes the chars where needed. For example in the attributes it doesn't escape apostrophes, while in node values it doesn't escape apostrophes and qoutes.
string xml = "<node>it's my \"node\" & i like it<node>";
using (XmlTextWriter xtw = new XmlTextWriter(@"c:\xmlTest.xml", Encoding.Unicode))
{
xtw.WriteStartElement("xmlEncodeTest");
xtw.WriteAttributeString("testAttribute", xml);
xtw.WriteString(xml);
xtw.WriteEndElement();
}
// RESULT:
/*
<xmlEncodeTest testAttribute="<node>it's my "node" & i like it<node>">
<node>it's my "node" & i like it<node>
</xmlEncodeTest>
*/
Each of the four ways is different, so use each one where you fell appropriate. You can't go wrong with SecurityElement though. :)
Subscribe to:
Posts (Atom)