Working with XML in .NET applications. How to work with XML - review of online services and xml editors

Present to your attention new course from the team The Codeby- "Penetration testing of Web Applications from scratch." General theory, Environment Preparation, Passive Fuzzing and Fingerprinting, Active Fuzzing, Vulnerabilities, Post-Exploitation, Tooling, Social Engeneering and much more.


XML DOM 2

The previous article described general concepts concerning XML. In this article we will learn how to perform basic actions related to changing, adding, searching in an XML file.

XML file that is used for the example.

Mazda 2007 BMW 2009

xml dom

IN this moment, our file contains the following structure:

Relationship between nodes in XML DOM, basic moments:

1. Any node in the DOM tree has a parent ParentNode. In our example, garage is the parent of both car elements, and both car elements are, in turn, parents of model and year elements.

How to get the parent for xml element and car?

Console.WriteLine(elmRoot["car"].ParentNode.Name); //Result: garage

2. A parent can have children ChildNodes. For example, for the garage node the children are both car elements. The car elements also have children model and year.

ChildNodes, is a collection that stores all child xml elements; to access the desired element, you need to specify its index. (The index always starts from zero!)

For example: how to get the first child element?

ElmRoot.ChildNodes;

3. As in ordinary life, a child can be born first FirstChild, or last LastChild.

If we take the car element as an example, then

FirstChild is model LastChild is year

4. In turn, there are also connections between the child elements; they can be brothers or sisters, if we draw parallels with real life.

A child may have, for example, a Previous Sibling brother and a Next Sibling brother

Console.WriteLine(elmRoot.ChildNodes.FirstChild.NextSibling.Name); //Result: year Console.WriteLine(elmRoot.ChildNodes.LastChild.PreviousSibling.Name); //Result: model

If the element is not found, then an exception is thrown: NullReferenceException, so when working with xml, always use try catch blocks.

Console.WriteLine(elmRoot.ChildNodes. LastChild.NextSibling.Name); Console.WriteLine(elmRoot.ChildNodes. FirstChild.PreviousSibling.Name);

LastChild is NextSibling;
FirstChild is PreviousSibling;

Using the methods described above, you can easily move to the desired node and get any value you need.

How to get the value of an xml element?

The xml value of an element can be obtained using the InnerText property, for example:

Console.WriteLine(elmRoot["car"].FirstChild.InnerText); //Result: Mazda

Another way to get the same xml element value:

Console.WriteLine(elmRoot.FirstChild.FirstChild.InnerText); //Result: Mazda

The sequence of movements along the DOM tree:

Garage -> car -> model -> Mazda

We get the year:

ElmRoot["car"].LastChild.InnerText; //Result: 2007

Subsequence:

Garage -> car -> year -> 2007

Another example: 3 ways to get the same result.

Console.WriteLine(elmRoot.LastChild.FirstChild.InnerText); Console.WriteLine(elmRoot["car"].NextSibling.FirstChild.InnerText); Console.WriteLine(elmRoot.ChildNodes.Item(1).FirstChild.InnerText); //Result: BMW

If you need to get the year for an element with the value Mazda:

Console.WriteLine(elmRoot.FirstChild.LastChild.InnerText); //Result: 2007

For BMW (two ways, get the same result)

Console.WriteLine(elmRoot.ChildNodes.Item(1).ChildNodes.Item(1).InnerText); Console.WriteLine(elmRoot.ChildNodes.ChildNodes.InnerText); //Result: 2009

How to change xml element values?

Using property InnerText() You can both get and change the value of an xml element, for example, change the year.

//Set a new value elmRoot.FirstChild.LastChild.InnerText = "2010"; //Display the new value on the console screen Console.WriteLine(elmRoot.FirstChild.ChildNodes.Item(1).InnerText); //Result: 2010

It must be remembered that all changes occur with the virtual xml file oh, if you open physical file, you will see that the year 2007 is still indicated in it.

In order for the changes to take effect, you need to use the Save method, for example:

ElmRoot.Save("xml file name or stream");

Now the information will be changed in the “physical” xml file.

How to get the number of child elements?

Console.WriteLine(elmRoot.FirstChild.ChildNodes.Count);

garage -> car contains 2 children: model and year

Console.WriteLine(elmRoot.FirstChild.FirstChild.ChildNodes.Count);

garage -> car -> model contains 1 child xml element.

Accessing Child Elements

by index

ElmRoot.ChildNodes.Name; elmRoot.ChildNodes.Name; //Result: car

Using a loop

Foreach (XmlNode nod in elmRoot.ChildNodes) ( Console.WriteLine(nod.Name); ) //Result: car, car

How to get xml element name?

elmRoot.Name; //Result: garage

Creating a new XML element

Let's create new element in our XML document, to make it different from the other two (car), let's call it bus.

When creating a new element, we will use the recommendation from the msdn website and instead of the standard new XmlElement, we will use the CreateElement method.

XmlElement elm = xmlDoc.CreateElement("bus");

Creating and adding a new xml element

Let's create a new xml element named "BUS".

XmlElement elmRoot = xmlDoc.DocumentElement; Console.WriteLine(elmRoot.ChildNodes.Count); //car, car XmlElement elmNew = xmlDoc.CreateElement("bus"); elmRoot.AppendChild(elmNew); Console.WriteLine(elmRoot.ChildNodes.Count); //3 car, car, bus xmlDoc.Save("xml file name");

Explanation:

1. First we get a root element to which we will attach new elements.

2. As a check, we will display the current number of child elements of the garage element: 2 (car and car)

3. Create a new BUS element

4. Using the method AppendChild adding a new element to the tree

5. Let's use the check again and display the current number of elements for the garage element, now there are 3 of them: car, car, bus.

6. For changes to affect the physical file, save

In the XML file itself, the new element will look like this:

How to add a new xml element?

Task: create a new XML element and add some text content to it, for example the year of manufacture.

String strFilename = @"C:\lessons\Auto.xml"; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(strFilename); XmlElement elmRoot = xmlDoc.DocumentElement; XmlElement elmNew = xmlDoc.CreateElement("bus"); XmlText new_txt = xmlDoc.CreateTextNode("2006"); elmRoot.AppendChild(elmNew); elmRoot.LastChild.AppendChild(new_txt); Console.WriteLine(elmRoot.ChildNodes.Name); //bus Console.WriteLine(elmRoot.ChildNodes.LastChild.InnerText); //2006 Console.Read();

In XML file:

2006

For clarity

Now let’s create a “bus” node with the same architecture as car, that is, add nodes: model, year and some text content.

Creating an XML Element with Children

string strFilename = @"C:\lessons\Auto.xml"; //create a new one xml document in memory XmlDocument xmlDoc = new XmlDocument(); //load the xml file into memory xmlDoc.Load(strFilename); //Get the root element XmlElement elmRoot = xmlDoc.DocumentElement; //Create 3 elements: bus, model, year XmlElement elmBUS = xmlDoc.CreateElement("bus"); XmlElement elmModel = xmlDoc.CreateElement("model"); XmlElement elmYear = xmlDoc.CreateElement("year"); //Set values ​​for elements: model, year XmlText year_txt = xmlDoc.CreateTextNode("2006"); //XmlText mod_txt = xmlDoc.CreateTextNode("liaz"); add otherwise //Add two to the bus element child elements: model and year elmBUS.AppendChild(elmModel); elmBUS.AppendChild(elmYear); //Add values ​​to the model and year nodes elmModel.InnerText = "liaz"; elmYear.AppendChild(year_txt); //Add a new xml element bus to the tree elmRoot.AppendChild(elmBUS); //Check if everything is added as it should Console.WriteLine(elmRoot.ChildNodes.FirstChild.InnerText); Console.WriteLine(elmRoot.LastChild.LastChild.InnerText); //If everything is in order, then use the Save method xmlDoc.Save("xml file name");

Result:

liaz 2006

How can you shorten this code? For example, as follows:

String PathXmlFile = @"C:\lessons\Auto.xml"; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(PathXmlFile); XmlElement elmRoot = xmlDoc.DocumentElement; XmlElement elmBUS = xmlDoc.CreateElement("bus"); XmlElement elmModel = xmlDoc.CreateElement("model"); XmlElement elmYear = xmlDoc.CreateElement("year"); //Add values ​​to the model and year nodes elmModel.InnerText = "liaz"; elmYear.InnerText = "2006"; elmBUS.AppendChild(elmModel); elmBUS.AppendChild(elmYear); elmRoot.AppendChild(elmBUS); //If everything is correct, then call the Save method xmlDoc.Save("xml file name");

Let's shorten the code a little more, for this we will use the InnerXml property:

XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(PathXmlFile); XmlElement elmXML = xmlDoc.CreateElement("bus"); string txt = " liaz" + "2006"; //InnerXml! elmXML.InnerXml = txt; //xmlDoc.DocumentElement (will be equal to garage) - this is another way to access the root element, the same as XmlElement elmRoot = xmlDoc.DocumentElement; xmlDoc.DocumentElement.AppendChild( elmXML); xmlDoc.Save(PathXmlFile);

Result

Get a list of elements using GetElementByTagName

GetElementByTagName returns XmlNodeList, which contains all descendant elements belonging to the specified element, for example, we need to get all the car models that are stored in the garage:

XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(strFilename); XmlNodeList modelName = xmlDoc.GetElementsByTagName("model"); foreach (XmlNode node in modelName) ( Console.WriteLine(node.InnerText); ) //Result: mazda, bmw, liaz

Access using index:

String PathXmlFile = @"C:\lessons\Auto.xml"; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(PathXmlFile); XmlNodeList modelName = xmlDoc.GetElementsByTagName("model"); Console.WriteLine(modelName.InnerText); //Result: liaz

How can I change the text content of a newly created "bus" element using the GetElementByTagName method?

String PathXmlFile = @"C:\lessons\Auto.xml"; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(PathXmlFile); XmlNodeList modelName = xmlDoc.GetElementsByTagName("model"); Console.WriteLine(modelName.InnerText); //Received the value: liaz

Or you can change the name liaz to Ikarus

Console.WriteLine(modelName.InnerText = "Ikarus");

Quite a long time has passed since I promised to talk about working with data in XML format when developing .NET applications. Promises must be kept. Please note that this article is not aimed at professional .NET developers, but at those who do not yet have significant experience in creating .NET applications.


Why should we work with XML?

If you don’t yet have a very good idea of ​​what XML is, then I recommend reading the article “XML is serious and for a long time” in “KV” No. for 2007. To save space for more important things, the XML format itself will not be analyzed here.

Before you start getting acquainted with the program code, you need to answer one fundamental question: why even include XML support in your application? I think many people have asked themselves this question regarding many technologies, and not all of them were included in applications after the answer. However, with XML the situation is somewhat different, and there are real reasons to use this format in many situations.

The main advantage of XML is that, being a text format by nature, it nevertheless perfectly allows storing and transmitting any data. Since this format is text, the problem of its cross-platform is solved by itself, and the problem of transmitting XML data is just as easily solved (as is, for example, done in SOAP). In addition, you can easily change the data transfer or storage format by adding new attributes and without worrying too much about compatibility with previous versions of the format, since applications using the old version will be able to read what they need without paying attention to new tags or attributes . Many applications use XML based file formats, many data transfer protocols are also based on XML, and the lists of both continue to grow.

Of course, on the other hand, XML is not very economical, because, as one of the visitors to the Computer News forum once correctly noted, XML documents often consist of 10% data and 90% tags. However, this largely depends on what tags you choose. You can write st. Melnikaite, 2, Can i . Although, to be honest, it seems to me that with the current hard drives and thick channels there is no point in being particularly compressed.

So in in capable hands XML is a powerful and convenient thing, and due to the ubiquity of this format, you can’t escape it at all. So let's move on to writing program code.

For programming we will use the main language of the .NET platform - C#. In order for as many readers as possible to practice with the given program code themselves, I will use the first version of C# and the .NET Framework.


Data recording

First, let's talk about writing data, because, you know, in order to read something from somewhere, you must first write something somewhere. And since you and I started programming, it’s not appropriate for us to create XML data manually. So let's first get started with writing the data into XML.

To begin, create a new project in Visual Studio, #Develop or C# Builder, and add System.Xml to the list of imported namespaces.

Responsible for writing XML data to the .NET Framework special class XmlTextWriter, which allows you to write XML data to an arbitrary stream. That is, we, generally speaking, can use it to write them both to a file and to a database, and send them to someone via the Internet, but now we will write everything to a file. You can redirect the output by changing the object's constructor (i.e., by passing during initialization not the file name and its encoding, but an object that is a data stream). However, it seems that I have already begun to get ahead of myself a little. Let's first get acquainted with the code responsible for writing data to our XML file.

String FileName = "c:\\demo.xml"; XmlTextWriter xml = new XmlTextWriter(FileName, System.Text.Encoding.Unicode); xml.Formatting = Formatting.Indented; xml.WriteStartDocument(); xml.WriteStartElement("rootelement"); for (int i = 0; i< 10; i++) { xml.WriteStartElement("subelement"); xml.WriteAttributeString("attrib1", "value1"); xml.WriteAttributeString("attrib2", i.ToString()); for (int j = 0; j < 10; j++){ xml.WriteStartElement("subsubelement"); xml.WriteAttributeString("attr", j.ToString()); xml.WriteEndElement(); } xml.WriteEndElement(); } xml.WriteEndElement(); xml.WriteEndDocument(); xml.Close();

The first line, I think, is quite clear - it’s simply recording the name of the file into which we will save the data. Next, we create an object of type XmlTextWriter (it is called, as you can see, xml), and it is with it that we will perform all further operations. Please note that when constructing an object, we also specify the encoding in which the XML will be written: in our example, this is Unicode. The next line, generally speaking, is not required, but it will make our XML document, as they say, human readable, that is, it will add the necessary indents and break it into lines. Without this, the entire document would be written in one line, which, although it saves space, makes it practically unsuitable for manual editing.

Document writing begins by calling the WriteStartDocument() method of our xml object. The line following it adds the root element “rootelement” to our XML document (let me remind you that for XML documents the root element must be present in a single copy). Next, in a cycle, we add ten more elements that do not carry any semantic load to our XML document, for each of which we set two attributes and ten more subelements. Please note that we can add a number to a string without explicitly converting the data, but if the number must entirely form a string, then it must be converted explicitly using the ToString() method. Also note that we must explicitly close each of the elements of our XML document, and then the entire document.

Now that our XML document has been successfully written, let's see how we can read data from it.


Reading data

Add a listBox component to the form of your application (unless, of course, it is a console application) so that you can monitor the result of reading the XML file. Well, if your program is a console program, then you can easily redirect the output to the console.

As usual, let's first get acquainted with the program code, and then we will look at what exactly this code does.

XmlTextReader xml = new XmlTextReader(FileName); xml.WhitespaceHandling = WhitespaceHandling.None; int i = 0; while (xml.Read())( if ((xml.NodeType == XmlNodeType.Element) & (xml.Name == "subelement")) ( listBox1.Items.Add("subelement " + i + " found") ; i++; listBox1.Items.Add(" " + xml.GetAttribute("attrib1")); listBox1.Items.Add(" " + xml.GetAttribute("attrib2")); xml.Name == "subsubelement"))( listBox1.Items.Add(" " + xml.GetAttribute("attr")); ) ) ) xml.Close();

For reading, as you may have noticed, we use another class, namely XmlTextReader. It is in the same namespace as the class we used to write the data. In the first line, we create an instance of XmlTextReader, named xml (here we assume that the FileName variable was already defined by us earlier). To skip empty lines if they somehow inexplicably appear in our just created XML file, we use next line in the given code snippet. The i variable is used to count the number of "subelement" elements found in the XML file from which the data is read.

Next comes the cycle of directly reading data from the file. The Read() method reads the next element of the XML document, and after reading it, we check what exactly we read. If it is indeed a "subelement" element, then we add information about the element read to listBox1, increment a variable containing the number of elements read, and then read the element's attributes. After reading the attributes, we organize a separate loop to read the subelements (note that we do not need a separate XmlTextReader for this) and the attributes of these subelements. As before, we enter all the information read into listBox1 to control the correctness of reading.

When reading XML files, in the same way as when writing them, when constructing an XmlTextReader, you can specify as a parameter the stream from which to read, and then you can read not only from files, but also from other sources , examples of which I have already given above. One useful feature of the XmlTextReader class should be noted: when reading, it does not load the entire XML document being read into memory, so it is convenient to parse large XML documents (for example, XML databases).


Behind the scenes

In general, the example we just discussed is too simple for real projects. Nowadays, when reading XML documents, they are usually validated using DTD, XML Schema or Relax NG. Validation is checking that the markup of an XML document conforms to some standard described in external file. Validation is needed so that document verification is not hard-wired into the program algorithm, but can be changed arbitrarily when the data format changes without updating the program code that reads or writes data. Unfortunately, now we won’t have time to sort out the validation, because, as you yourself understand, the volume of a newspaper article has certain limitations.

Another interesting and useful practical point regarding working with XML data is XSL data transformation. This transformation is applied to data when it is displayed on HTML pages and, in fact, is simply applying a specific web page template to an XML file containing some data. Since the lion's share of current use of XML data is somehow in the World Wide Web, then it would be very, very nice to consider XSL transformations.

So, I think, this article will have a continuation - but, of course, only if you yourself (that is, the readers of Computer News) ask about it on the forum or in a letter to my email mailing address. For now, that’s probably all about using XML in .NET applications. I hope this information is useful to you.

Working with XML Data in ASP.NET 2.0 Applications, the XmlDataDocument Object and the XML Control

This module focuses on how you can work with XML data from ASP.NET applications.

XML stands for Extensible Markup Language(eXtensible Markup Language), although XML itself is not a language. XML is a set of rules used to create your own markup languages. For example, imagine that we have the following data about an employee:

This data, of course, can be presented in any way you like: in the form of a table in relational database data, in the form Excel tables or HTML, as a table in Word document or in the form text document ASCII, as a *.csv file, etc. If we present them in the format of the XML-compatible markup language ABML (Address Book Markup Language) that we invented, they will look like this:

Alexander Ivanov

Nevsky pr, 1

Saint Petersburg

555-55-55

A little about how to decipher this code. The first two lines are a prologue (using it is, in principle, optional, but highly recommended). Line

is called an XML Declaration and indicates that this file conforms to the XML 1.0 specification, adopted as a recommendation by the World Wide Web Consortium on February 10, 1998. Line

is called a Document Type Definition and means that the structure of the language to which this document corresponds is described in the abml.dtd file (you can also use internal DTDs when the language description is located directly in the document). Nowadays, rather than DTDs, XML Schema is more often used to describe the structure of XML-compatible languages ​​- they are easier to access and provide more capabilities, in particular, when describing various data types. The same line using XML Schema could look like this:

depending on where the Schema itself - the description of this language - is located in the abml.xml file or on the Web server (corporate schema storage from Microsoft - BizTalk Server).

An example XML Schema for our language might look like this:

xmlns="urn:schemas-astrosoft-ru:abml maxOccurs="*" />

XML is a formalized set of rules for “marking up” a document—that is, highlighting its logical structure. What's inside any XML-compliant document can be broken down into two categories: markup and the content itself. All markup information must begin with either an ampersand character (&) or a left angle bracket character (<). В XML существует шесть типов информации разметки: элементы, атрибуты, комментарии, инструкции обработки, ссылки на сущности и разделы CDATA.

· Elements(elements) is the most common type of markup information. The element identifies a logical component of a document. A typical document consists of opening and closing tags, which may surround content, another element, or both. Tags with element names are enclosed in angle brackets. Here is an example element:

4296 Razor Hill Road

· Attributes(attributes) consist of an attribute name/attribute value pair and are applied to elements. Attributes should be placed after the element name in the opening tag. For example, the attributes are width and height:

· Comments(comments) is any text that will be ignored by the XML processor. Example:

· Processing instructions(processing instructions) are used to pass information to the application processing the XML document. The processing instruction syntax looks like this:

· Entity references Entity references are used to place reserved characters or reserved words into a document. For example, we need to insert a left angle bracket (<), которая является зарезервированным символом XML. Просто так вставить в текст документа мы ее не сможем: приложение, работающее с документом, решит, что она относится к разметке. Поэтому нам необходимо использовать сочетание символов <. lt означает less than(less than), and the ampersand (&) and semicolon (;) highlight an entity reference.

· CDATA section(CDATA section) is a piece of text that is not processed like the rest of the XML document, but is passed directly to the application. This tool can be useful, for example, when passing some code to an application.

XML syntax principles:

· XML documents are composed of Unicode characters (Unicode is a 16-bit character set that allows documents to be displayed in any language).

· XML is case sensitive. Tags And there are different tags in it.

· Whitespace is invisible characters such as space (ASCII 32), tab (ASCII 9), carriage returns (ASCII 13), and line feeds (ASCII 10). White space is ignored within tags, but is preserved in character data (that is, between the opening and closing tags). White space in character data is passed to the processing application.

· Many XML components must have names (the most obvious example is elements and attributes). The XML naming rules are as follows: The XML name must begin with a letter or underscore, followed by any number of letters, numbers, hyphens, underscores, or periods, for example:

My_Unique_Tag_Identifier-123 2_This_name_is_incorrect

· The XML component name cannot begin with xml characters (either uppercase or lowercase). Such names are reserved by the specification creators for official purposes.

· Character values ​​must be enclosed in single or double quotes.

· In XML, the nesting order of tags must be strictly observed.

· Any opening tag in XML must have a corresponding closing tag.

· An empty tag in XML is written as an opening tag, preceded by a right angle bracket with a forward slash (/).

· There can only be one root element in an XML document.

What are the advantages of storing data in XML over traditional binary formats? Why are most major software manufacturers currently either completely switching to working with data in an XML-compatible format (for example, Microsoft Office 2003), or planning to switch in the near future? The main reason is that XML data is very easy to transfer between a wide variety of applications and very easy to transform. Additional points related to the benefits of XML:

  • Independent data format - data in XML format can be opened in any XML-compatible (more precisely, compatible with a specific schema) application. Example: at any enterprise, documents are stored in a variety of formats - formats of different versions of Word, text, HTML, PDF, etc. Because of this, a lot of problems arise, which can be radically solved with the help of XML.
  • The general principle is one data source (XML document), many views. This can be clearly demonstrated using the example of a Web site that needs to be accessed from different browsers and via WAP.
  • Much easier data transfer “through” applications. Examples are the passage of documents through a supply chain, or the passage of data between dissimilar software products in one enterprise (which is necessary very often).
  • Improved data search capabilities. Firstly, there is no need to access documents of different binary formats, and secondly, the hierarchical structure of XML documents makes searching easier.
  • Easier application development - There is no need to implement support for a large number of different binary data formats in applications.
  • Data in text format (XML - Unicode standard) is easier than binary to store on various platforms and safer (from the point of view of the absence of malicious binary code) to be transmitted over networks. A whole direction in application development is XML Web services.

Well-formed XML is XML code that conforms to the syntax requirements of that language (for example, each opening tag has a corresponding closing tag). Valid XML is valid in terms of the logical structure of the language (for example, elements are nested correctly) as defined in the DTD or XML Schema.

A little bit of XML terminology that will be used in this course:

· XSD - XML ​​Schema Definition, a description of the structure of an XML document commonly used in VS .NET. Usually it is located in files with the *.xsd extension. Special tags are used inside the schema . Each element marked with this prefix belongs to the XML Schema. Within XML Schema you can use namespaces. For example, to indicate that two namespaces pertaining to W 3C XML Schema and Microsoft Office 10 Data Schema are used within a schema, you can use the tag

xmlns:od="urn:schemas-microsoft-com:officedata">

To define a Last Name string element within a schema that can appear 0 or more times in a document, you can, for example, use the following tag:

type="string">

· to describe transformations of XML-compatible documents, documents in a special programming language XSLT (eXtensible Stylesheet Language Transform) are used. The language itself is, of course, also XML-compatible. XSLT uses three types of documents:

o source document. This XML document is "input" for transformation. In our case, this could be a document like this:

xml-stylesheet type="text/xsl" href=" Employees1.xsl"?>

Stuart Munson

Programmer

Robert Brown

Tester

o XSLT style sheet document - an XML-compatible document that describes the rules for carrying out transformations. In our case, an example of this document could be like this:

xmlns:xsl=" http://www.w3.org/1999/XSL/Transform"

version=" 1.0 ">



o document - the result of transformations. For example, when applying our transformation, the employee's name will be marked in red and his position will be marked in blue.

· XPath is a special language that can be used to navigate through a tree of XML elements. When using the XPath object model, an XML document is represented as a tree of nodes. The information is contained in the properties of these nodes.

· DOM (Document Object Model) - representation of an XML document tree in RAM. DOM allows you to navigate and edit an XML document. Standard DOM properties, methods, and events are defined in a document adopted by the W3C. In ASP.NET, you can use the DOM to create an XML document and send it to the user's browser. Another option is for a client script to create an XML document on the client using the DOM and send it to the Web server.

· XQuery is a specialized language for querying information stored in XML documents. XQuery is largely based on XPath.

It must be said that XML is a standard format for working with data in ADO.NET. About the XML format and how it can be used with DataSet - below.

The possibilities of using XML when working with DataSet are as follows:

· DataSets can serialize data in XML format. The DataSet's schema (including tables, columns, data types, and constraints) is defined in an XML Schema (.xsd file).

· data exchange from the DataSet with remote clients is required to be carried out in XML format;

· XML can be used to synchronize and transform data into a DataSet.

A little more about the interaction between XML and DataSet:

· you can not only create an XML Schema based on a DataSet (as mentioned above, this is done using the WriteXmlSchema method), but also vice versa - generate a DataSet based on the information from their XML Schema (for this, use the ReadXmlSchema method). It is possible to generate a DataSet even without a schema - simply based on an XML document. The InferXmlSchema method is intended for this purpose.

· a method is provided for the DataSet object ReadXML, which allows you to read an XML text document (an XML text data stream) into a DataSet. Another method WriteXML, allows you to save the contents of a DataSet in an XML-compatible format. This feature makes it very easy to organize data exchange between different applications and platforms.

· You can create an XML representation (XmlDataDocument object) based on information from the DataSet. It turns out that you can work with information in a DataSet in two ways: conventional relational (with the DataSet itself) and XML methods. Both views are automatically synchronized (when changes are made through either view).

· You can apply XSLT transformations to data that is stored in a DataSet.

Now let's talk about how all this looks in practice.

Dim ds As New DataSet()

ds.ReadXml(Server.MapPath("filename.xml"))

The MapPath method for a special Server object allows you to convert the virtual path of a file in a Web application to a physical path.

Whether the DataSet structure is automatically generated from the XML file or remains the same depends on whether it has already been generated in that DataSet and whether the ReadXml XmlReadMode optional parameter was specified.

Dim ds As New DataSet()

Dim da As New SqlDataAdapter(_

"select * from Authors", conn)

da.Fill(ds)

ds.WriteXml(Server.MapPath("filename.xml"))

There are two more methods that allow you to get data in XML format from a DataSet and put it in a string variable. These are the GetXml and GetXmlSchema methods. An example might look like this:

DimstrXmlDSAsString =ds.GetXml()

A DataSet often contains DataTable objects connected to each other by DataRelations (that is, tables with a Primary and Foreign key). When exporting to XML, information from the parent table can be supplemented with information from the child table. Records from the subordinate table will appear as nested elements for records from the main table. To implement this feature, you need to set the Nested property to True for the DataRelation object in the DataSet (the default is False).

Let's say we just export the data without using this property:

Dim ds As New DataSet()

'fill the DataSet

...

Dim parentCol As DataColumn = _

ds.Tables("Publishers").Columns("pub_id")

Dim childCol As DataColumn = _

ds.Tables("Titles").Columns("pub_id")

ds.Relations.Add(dr)

ds.WriteXml(Server.MapPath("PubTitlesNotNested.xml"), _

XmlWriteMode.IgnoreSchema)

The XML code looks like this:

title1

1

40.00

title2

2

60.00

title3

1

30.00

1

pub1

2

pub2

and now we use it to set the Nested property for the DataRelation object to True:

Dim dr As New DataRelation _

("TitlePublishers", parentCol, childCol)

dr.Nested = True

ds.Relations.Add(dr)

ds.WriteXML(Server.MapPath("PubTitlesNested.xml"), _

XmlWriteMode.IgnoreSchema)

The XML code turns out completely different. Each element of the Pub type contains Titles elements released by this publisher:

1

pub1

title1

1

40.00

title3

1

30.00

2

pub2

title2

2

60.00

XmlDataDocument is an in-memory XML representation of data in a DataSet. An XmlDataDocument is inextricably linked to a DataSet. Any changes made to the XmlDataDocument are immediately reflected in the DataSet and vice versa. Below we will talk about techniques for working with XmlDataDocument.

DataSet is a relational representation of data, while XmlDataDocument is hierarchical. Using XmlDataDocument is very convenient, since working with data in XML format only through a DataSet can be difficult. For example, if you load data from an XML file into a DataSet and then unload it back, it may well turn out that the file will be unrecognizable: formatting will be lost, quite possibly the order of elements, perhaps elements that were ignored due to inconsistency with the schema , defined for the DataSet.

You can put an XML document directly into an XmlDataDocument, or you can create it based on a DataSet. The code for the first option might look like this:

Dim objXmlDataDoc As New XmlDataDocument()

objXmlDataDoc.Load(Server.MapPath("file.xml"))

or like this:

objXmlDataDoc.DataSet.ReadXml(Server.MapPath("file.xml"))

There won't be any difference.

Or you can first create a DataSet, fill it with data, and then create an XmlDataDocument based on it:

Dim ds As New DataSet()

'fill in ds

...

Dim objXmlDataDoc As New XmlDataDocument(ds)

Once the XmlDataDocument object is created, you can perform various actions on it:

· bind to DataGrid and other controls:

dg.DataSource = objXmlDataDoc.DataSet

· get the required string (it is returned as an XmlElement object):

Dim elem As XmlElement

elem = objXmlDataDoc.GetElementFromRow_

(ds.Tables(0).Rows(1))

· use the full set of DOM properties and methods. XmlDataDocument inherits these properties and methods from the XmlDocument object

· apply XSLT transformations (XslTransform objects are used for this purpose).

Learn more about XSLT transformations:

XSLT allows you to transform a source XML document into another document that differs in format and structure. For example, using XSLT, an XML document can be converted to HTML code for display in a Web application. ASP.NET uses the XslTransform class to perform XSLT transformations.

What is it like to work with him?

· to carry out transformations, you first need to create a DataSet and the corresponding XmlDataDocument :

Dim ds As New DataSet()

'fill in DataSet

...

Dim xmlDoc As New XmlDataDocument(ds)

· next action - create an XslTransform object:

Dim xslTran As New XslTransform()

· use the Load method of this object to load the transformation into it:

xslTran.Load(Server.MapPath("PubTitles.xsl"))

· create an XmlTextWriter object (it will be used to display the transformation results):

Dim writer As New XmlTextWriter _

(Server.MapPath("PubTitles_output.html"), _

System.Text.Encoding.UTF8)

· We perform the transformation itself using the Transform method of the XslTransform object. This method has several options. One way to use it might look like this:

xslTran.Transform(xmlDoc, Nothing, writer)

· close the Writer object:

writer.Close()

To work with XML on a Web form, you can do without a DataSet object (and controls designed to display data from a relational source). You can use the XML Web Server Control instead. It allows you to display XML documents themselves or the results of their transformations on a Web page. XML code can be passed to this control in different ways:

· directly open them from disk (via the DocumentSource property). In this case (if you have not applied XSLT transformations), the XML document will be output to the form "as is":

XML Example

TransformSource="MyStyle.xsl" runat="server" />

· open them as objects and pass them to this control (via the Document property). In our case XML Web Server Control is called Xml1:

Private Sub Page_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load

Dim xmlDoc As System.Xml.XmlDocument = _

New System.Xml.XmlDocument()

xmlDoc.Load(Server.MapPath("MySource.xml"))

Dim xslTran As System.Xml.Xsl.XslTransform = _

New System.Xml.Xsl.XslTransform()

xslTran.Load(Server.MapPath("MyStyle.xsl"))

Xml1.Document = xmlDoc

Xml1.Transform = xslTran

End Sub

· simply programmatically generate XML code and pass that XML code to Web Server Control (via the DocumentContent property)

· in general, directly enter the XML code into the XML Web Server Control tag:

Frank Miller

Judy Lew

perform the transformation and transfer the transformation results to it

An example that illustrates all these possibilities is presented below:

Document="XmlDocument object to display"

DocumentContent="String of XML"

DocumentSource="Path to XML Document"

Transform="XslTransform object"

TransformSource="Path to XSL Transform Document"

runat = "server ">

You can add an XML Web Server Control to a Web form by simply dragging this control from the ToolBox or programmatically:

< asp:Xmlid="xmlCtl"runat = "server " />

XmlCtl.Document.Save (Server.MapPath("xmlResult.xml "))

Language is not the son, but the father of thought.
Oscar Wilde

Abbreviation XML stands for Extensible Markup Language, translated as “extensible markup language”. Like HTML, it is a subset of SGML (Standard General Markup Language), the “grandfather” of markup languages. We have come across the XML format more than once. This is the format of configuration files, a file describing object data sources.

XML is a universal, platform-independent standard for describing information that can be used to represent hierarchical data and unify the information transferred. Without knowledge of it, it is impossible to understand SOAP and, therefore, web services. XML has become the de facto standard for data transmission on the Internet. The XML and related formats standard is defined by the W3C (World Wide Web Consortium). For example, we create aspx pages in the XHTML format - transitional between HTML and XML, the standard of which is also defined by the W3C. The XHTML standard imposes stricter rules on the correct formation of a document, similar to the rules of XML.

Let's understand the main difference between XML and HTML. XML is designed to describe data and focus on what exactly it is. HTML is designed to show data and focuses on how the data looks. If in traditional HTML the concepts of “presentation” and “visualization” are often confused, then when working with XML we clearly separate these concepts. XML tags are not predefined by the creators of the language, unlike HTML tags. Each document author defines his own tags.

The standard requires that a program that processes an XML document must stop if it encounters an error. And if the browser detects an unclear tag in the HTML, or the absence of a closing tag, it simply ignores it.

At the beginning of an XML document, its declaration, or prologue, always appears. It specifies the version of the XML standard to which it conforms.

is an error in XML.

Tags can have attributes. Attribute values ​​must be enclosed in quotation marks. The order of the attributes does not matter. There may be text between the opening and closing tags. XML preserves all whitespace found in the text. If there is no text, you can use an abbreviated form of notation. Example XML tag:

This is a short form of the tag

Does this remind you of anything? The rules for describing ASP.NET elements are exactly the same.

There is an xmlns attribute that defines the namespace. Its value can be any unique name. There is an agreement to use URLs because they are unique. Namespaces have a meaning similar to how they are used in the .NET Framework - to avoid mixing up similar names used by different developers. The namespace name is separated from the name by a colon.

XML files represent hierarchical information that can be represented as a single-rooted tree.

XML documents that satisfy all syntax requirements are called well-formed. To describe data, XML uses DTD (Document Type Definition) - a definition of the document type. If the file matches the DTD, it is considered valid.

Browsers IE 6.0, FireFox 1.5 display XML files with syntax highlighting. Parent nodes can be expanded and closed. For example, when closed, the root node of the BirthDay.xml file looks like this:

The Visual Studio and VWD Express development environments check the correctness of xml documents right during editing.

AdRotator

Control element AdRotator allows you to display advertising banners and automatically replace them with others. The banners themselves are described in an XML file or other data source. The advertisement is updated every time the page is refreshed. The AdvertismentFile property specifies the name of the XML file. The skeleton of an XML file is as follows.

Inside the Advertisements node there are nodes

These nodes have 5 attributes, all of which are optional.

An example of an AdvertismentFile file, it is called ads.xml.

fixed.gif http://www.im.am Free hosting 40 hosting logo2.jpg http://www.nv.am Newspaper "New Time" 50 news summer.jpg http://www.utro.ru Singer Jasmine was beaten by her husband! 100 yellow news

A control element is placed on the page. Its AdvertisementFile property points to this file.

If the Keyword property is set, the control displays only advertisements that match its content. Since it can be changed dynamically, advertising can be tailored to the user's needs. The keyword must appear at least once in the ad file, otherwise there will be an empty rectangle instead of an ad.

In previous versions of ASP.NET, you could only work with XML files. You can now use any data source by binding to the data source control. In this case, you must specify at least 3 source fields in the ImageUrlField, NavigateUrlField and AlternateTextField properties.

Document Conversion Files

It is known that CSS (Cascading Stylesheets) are often used to format HTML files, although this is not necessary since browsers associate a certain appearance with all tags. Element

Sets the paragraph - bold font - the browser knows how to show them.

Since XML does not use predefined tags, their meaning can be anything:

could mean an HTML table, or could mean a wooden table. Therefore, browsers display XML documents "as is". You can also specify CSS files for XML documents, but this is not recommended.

To set the display format of XML documents, style sheets are used XSL. XSL- Extensible Stylesheet Language is much richer in capabilities than CSS. XSL is more than just a style sheet.

The same XML file can be linked to different XSL tables, including programmatically.

XSL consists of 3 parts:

  1. XSLT - a method for transforming XML documents
  2. XPath - a method for specifying parts and paths to XML elements
  3. XSL Formatting Objects - methods for formatting XML documents

The most important part of XSL is the XSLT Transformation language. It is used to transform XSL documents into other document types or other XSL documents. XSLT is often used to convert an XSL document into HTML format.

To create an XSLT document, select XSLT file in the file creation dialog. VS 2005 creates a stylesheet framework. Because a style sheet is itself an XML document, it begins with an XML declaration.

If you've studied CSS, you know that style rules are used. A rule consists of a selector and a style statement in curly braces.

This tag contains a template HTML file. The comment reminds you that you need to insert XSL elements there.

Let's look at creating XSLT files using an example. Create an XML file "Quotes.xml" in the App_Data folder

We wanted the best, but it turned out as always. Victor Chernomyrdin America is a continent so named because Columbus discovered it. Georges Elgozy It makes me furious to think about how much I would have learned if I hadn't gone to school. George Bernard Shaw Much is invented in order not to think. Karel Capek If you tell the truth, you will still get caught sooner or later. Oscar Wilde He should be president if he is not hanged before then. Mark Twain

To output XSLT transformations for each XML element, use the xsl:for-each XSL tag. The :for-each element locates elements in the XML document and repeats the pattern for each one.

Data can be sorted using the xsl:sort tag, which must be inside the xsl:for-each element:

The final look of the transformation file:

Famous Quotes

Quote Author

If you want to see the result of the document transformation in the browser, include a declaration after the XML declaration

,

or select Show XML Output from the XML menu and specify the transform file.

The same XML document can be transformed using another XSL file:

Masters of Aphorism



The result will be quotations separated by a horizontal line.

Document Schema Definition Files

According to the modern standard, a valid document must match the file associated with it XSD(XML Schema Definition) - An XML schema definition file that defines a particular language, that is, describes what elements and types can appear in a document. XSD schemas are intended to replace DTD (Document Type Definition), the difference between them is that XSD files themselves also use XML syntax. XSD schemas allow you to determine which tags are allowed, whether they are required or not, whether they can be repeated in a document, and so on. Thus, XML describes data, and XSD describes the structure of that data, or metadata. In programming terms, XSD is a description of types, while an XML file describes objects of those types. A working draft of the XSD 1.1 standard is available at http://www.w3.org/TR/2003/WD-xmlschema-11-req-20030121/.

The schema definition file begins with a description of the namespace prefix, which is then included in all elements of the file. http://tempuri.org is used to set the URI for ASP.NET namespaces.

For example, this definition specifies that the element "Author" is of type string, must appear once and only once, and if not specified, takes on the value "Pushkin".

The maxOccurs="unbounded" parameter specifies that the element can appear any number of times.

The ref parameter allows you to refer to a global element or attribute already described in a given file to avoid repeating the same elements.

  1. define simple and complex types.

XSD has predefined types - much the same as .NET. They are converted to .NET types while the application is running. Based on them, you can build complex types similar to the structures of programming languages. A complex type consists of a sequence of element declarations. Let's define a complex type

Tag specifies that elements in a given type must appear in a given order. If the tag were used , then the elements could appear in any order.

Tag similar to a structure with options. It specifies that an element of a given type must have only one of its nested elements.

The following example defines a simple type nested within the MyValue element definition.

  1. Add new groups and attribute groups.

A complex type definition can include attributes. Let's say we want to build a schema for a file like this:

Attributes can only be of simple types.

  1. Add annotations.

Annotations allow you to insert descriptions of existing elements, thereby adding documentation to the file.

Quotes from various authors

is intended for readers of the file, and for file processing programs.

You can edit XSD files in Visual Studio 2005 both through the source code and using the designer. For an XML document, you can automatically generate a corresponding schema. In the XML document properties window, you can specify both a schema file and a transform file. In this case, the studio automatically checks the file for compliance with the schema, and even IntelliSense substitutes tags from this file.

XmlReader class

Using the XmlReader class, you can retrieve data from XML documents faster than other methods.

XmlReader is an abstract class. To start reading, an object of the XmlReaderSettings class is passed to the static Create method. This function counts the number of nodes in a document.

using System.Xml;

using System.IO;

private int CountNodes(string xmlFile) ( int NodesCount=0; XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = true; settings.IgnoreComments = true; using (XmlReader reader = XmlReader.Create(xmlFile, settings)) ( while ( reader.Read()) ( if (reader.NodeType == XmlNodeType.Element) ( NodesCount++; ) ) return NodesCount;

The XmlReader class allows you to retrieve CLR classes from a document. Let us have a restaurant menu.

Let's write a function that will calculate the sum of prices and calories in the menu.

The class provides reading and in-memory storage of XML documents for transformations using XSL. You can navigate the document in any direction and gain random access to any element using XPath expressions.

Let's take the XML document "Quotes.xml" and the XSL transformation file "Quotes.xsl". The result of the XML document transformation will be sent to the output stream of the page.

<% XPathDocument doc = new XPathDocument(Server.MapPath("App_Data\\Quotes.xml")); XslCompiledTransform xsl = new XslCompiledTransform(); xsl.Load(Server.MapPath("App_Data\\Quotes.xsl")); xsl.Transform(doc, null, Response.OutputStream); %>

Due to the fact that table tags are defined in the transformation file, a table with the necessary information will appear on the page.

XML Control

The XML control provides a way to transform an XML document using an XSL style sheet. The DocumentSource property allows you to specify the XML file in which the data is located, and the TransformSource property allows you to specify the XSLT transformation file.

In the previous example, the same result could be achieved by placing an XML control on the page.

XMLDataSource

The XMLDataSource data source element provides a simple way to connect XML documents as data sources to elements that display information. You can also specify an XPath query to filter the data. Like SqlDataSource, it allows you to edit, delete, add data records. To do this, you need to access the XmlDataDocument object located in it by calling the GetXmlDocument method. After editing, the document is saved using the Save method.

Unlike tabular data in a DBMS, data in XML files is hierarchical, so XMLDataSource is convenient to bind to hierarchical controls, such as Menu.

XML Data Binding Syntax

As applications use XML data more and more frequently, a method has been introduced to bind data obtained from an XMLDataSource.

These methods work in the same way as Bind and Eval, which were discussed in Lecture 7.

Let's apply this syntax to a DataList element that receives data from an XmlDataSource:

Conclusion

In this lecture we looked at working with XML data. XML provides a universal way to describe and exchange structured information, independent of applications and developers. This completes the consideration of working with data sources.

In the first article in the .NET blog, “Working with XML,” people in the comments demanded an article on LINQ to XML. Well, let's try to reveal the principles of operation of this new technology from Microsoft.

Let's create a base for maintaining a catalog of audio recordings. The database will consist of tracks:

  • Name
  • Executor
  • Album
  • Duration
We will learn how to add, edit, delete and make various selections from our database.

First, let's create a console application (I write my projects in C#, but the essence will generally be clear to everyone) and connect the necessary namespace

Using System.Xml.Linq;

Generating XML Files

Let's create an XML file of our database containing several test records using LINQ:

//set the path to our working XML file string fileName = "base.xml"; //counter for the track number int trackId = 1; //Creation by nested constructors. XDocument doc = new XDocument(new XElement("library", new XElement("track", new XAttribute("id", trackId++), new XAttribute("genre", "Rap"), new XAttribute("time", " 3:24"), new XElement("name", "Who We Be RMX (feat. 2Pac)"), new XElement("artist", "DMX"), new XElement("album", "")), new XElement("track", new XAttribute("id", trackId++), new XAttribute("genre", "Rap"), new XAttribute("time", "5:06"), new XElement("name", "Angel (ft. Regina Bell)"), new XElement("artist", "DMX"), new XElement("album", "...And Then There Was X")), new XElement("track", new XAttribute("id", trackId++), new XAttribute("genre", "Break Beat"), new XAttribute("time", "6:16"), new XElement("name", "Dreaming Your Dreams") , new XElement("artist", "Hybrid"), new XElement("album", "Wide Angle")), new XElement("track", new XAttribute("id", trackId++), new XAttribute("genre" , "Break Beat"), new XAttribute("time", "9:38"), new XElement("name", "Finished Symphony"), new XElement("artist", "Hybrid"), new XElement(" album", "Wide Angle")))); //save our document doc.Save(fileName);

Now, after launching, an XML file with the following content will appear in the folder with our program:
Who We Be RMX (feat. 2Pac) DMX The Dogz Mixtape: Who's Next?! Angel (ft. Regina Bell) DMX ...And Then There Was X Dreaming Your Dreams Hybrid Wide Angle Finished Symphony Hybrid Wide Angle

To create such a file using XmlDocument, the code required about 2 times more. In the code above, we used the constructor of the XDocument class, which takes as a parameter a list of child elements with which we initially want to initialize the document. The XElement constructor used takes as a parameter the name of the element that we are creating, as well as a list of initializing elements. Conveniently, we can set both new XElement and XAttribute in these elements. The latter will be rendered into our file as attributes independently. If you do not like using such nesting of constructors and you consider such code to be cumbersome, then you can rewrite it in a more traditional version. The code below will output a similar XML file:

XDocument doc = new XDocument(); XElement library = new XElement("library"); doc.Add(library); //create the "track" element XElement track = new XElement("track"); //add the necessary attributes track.Add(new XAttribute("id", 1)); track.Add(new XAttribute("genre", "Rap")); track.Add(new XAttribute("time", "3:24")); //create the element "name" XElement name = new XElement("name"); name.Value = "Who We Be RMX (feat. 2Pac)"; track.Add(name); //создаем элемент "artist" XElement artist = new XElement("artist"); artist.Value = "DMX"; track.Add(artist); //Для разнообразия распарсим элемент "album" string albumData = "!} The Dogz Mixtape: Who's Next?!"; XElement album = XElement.Parse(albumData); track.Add(album); doc.Root.Add(track); /* *add the remaining elements in the same way */ //save our document doc.Save(fileName);

Naturally, you need to choose the necessary method depending on the situation.

Reading data from a file

//set the path to our working XML file string fileName = "base.xml"; //read data from the file XDocument doc = XDocument.Load(fileName); //we go through each element in the new library //(this element is immediately accessible through the doc.Root property) foreach (XElement el in doc.Root.Elements()) ( //Output the element name and the value of the id attribute Console.WriteLine(" (0) (1)", el.Name, el.Attribute("id").Value); Console.WriteLine(" Attributes:"); //we display all the attributes in a loop, at the same time see how they convert themselves into a string foreach (XAttribute attr in el.Attributes()) Console.WriteLine(" (0)", attr); Console.WriteLine(" Elements:"); // print the names of all child elements and their values ​​in a loop foreach (XElement element) in el.Elements()) Console.WriteLine(" (0): (1)", element.Name, element.Value )

Here in the code, I think, there is nothing complicated and comments are provided. After running our program, the following result will be displayed in the console:

Track 1 Attributes: id="1" genre="Rap" time="3:24" Elements: name: Who We Be RMX (feat. 2Pac) artist: DMX album: The Dogz Mixtape: Who"s Next?! track 2 Attributes: id="2" genre="Rap" time="5:06" Elements: name: Angel (ft. Regina Bell) artist: DMX album: ...And Then There Was X track 3 Attributes: id= "3" genre="Break Beat" time="6:16" Elements: name: Dreaming Your Dreams artist: Hybrid album: Wide Angle track 4 Attributes: id="4" genre="Break Beat" time="9: 38" Elements: name: Finished Symphony artist: Hybrid album: Wide Angle

Changing data

Let's try to go through all the library nodes and increase the Id attribute of the track element by 1.
(I will not write further the declaration of the path to the file and the result of the output to the console, so as not to overload the article with unnecessary information, I compiled everything, everything works :)):

//Get the first child node from library XNode node = doc.Root.FirstNode; while (node ​​!= null) ( //check that the current node is an element if (node.NodeType == System.Xml.XmlNodeType.Element) ( XElement el = (XElement)node; //get the value of the id attribute and convert it in Int32 int id = Int32.Parse(el.Attribute("id").Value); //increase the counter by one and assign the value back id++; el.Attribute("id").Value = id.ToString() ; ) //move to the next node node = node.NextNode ) doc.Save(fileName);

Now let's try to do this in a more correct way for our tasks:

Foreach (XElement el in doc.Root.Elements("track")) ( int id = Int32.Parse(el.Attribute("id").Value); el.SetAttributeValue("id", --id); ) doc.Save(fileName);

As you can see, this method suited us better.

Adding a new entry

Let's add a new track to our library, and at the same time calculate the following unique Id for the track using LINQ:

Int maxId = doc.Root.Elements("track").Max(t => Int32.Parse(t.Attribute("id").Value)); XElement track = new XElement("track", new XAttribute("id", ++maxId), new XAttribute("genre", "Break Beat"), new XAttribute("time", "5:35"), new XElement("name", "Higher Than A Skyscraper"), new XElement("artist", "Hybrid"), new XElement("album", "Morning Sci-Fi")); doc.Root.Add(track); doc.Save(fileName);

With such a raised query to all elements, the maximum value of the id attribute of the tracks is calculated. When adding, we increment the resulting maximum value. Adding an element itself comes down to calling the Add method. Please note that we are adding elements to Root, since otherwise we will break the structure of the XML document by declaring 2 root elements there. Also, do not forget to save your document to disk, since until saving, no changes in our XDocument will be reflected in the XML file.

Removing items

Let's try to remove all DMX artist elements:

IEnumerable tracks = doc.Root.Descendants("track").Where(t => t.Element("artist").Value == "DMX").ToList(); foreach (XElement t in tracks) t.Remove(); !}

In this example, we first selected all the tracks whose child element artst met the criteria, and then deleted these elements in a loop. The call at the end of the selection to ToList() is important. By doing this, we record in a separate memory area all the elements that we want to delete. If we decide to delete from the set of records that we are going through directly in the loop, we will get the removal of the first element and the subsequent NullReferenceException. So it's important to remember this.
According to the advice of xaoccps, you can delete it in a simpler way:
IEnumerable tracks = doc.Root.Descendants("track").Where(t => t.Element("artist").Value == "DMX"); tracks.Remove(); !}
In this case, there is no need to convert our resulting result to a list by calling the ToList() function. Why was this method not originally described in