How to filter data in an XML file

In .NET technology, XML is a widely supported file format, and it serves as the internal storage format for the Dataset in ADO.NET.

In the following scenario, we will demonstrate how to filter the contents of an XML file and store the filtered result in a newly created XML file. Specifically, we will be working with an XML file named "Product.XML" that contains a field called "Product_Price". Our objective is to establish a search criteria where the "Product_Price" is greater than or equal to 3000. The filtered result will then be stored in a newly created XML file named "Result.XML".

XmlDocument object

To accomplish this, we will employ various XML-related functionalities provided by the .NET framework. First, we will load the original XML file, "Product.XML", into an XmlDocument object, which allows us to manipulate the XML data.

Next, we will create a new XmlDocument object to store the filtered results. We will iterate through the nodes of the original XML document and examine the value of the "Product_Price" field for each node. If the price meets our search criteria (i.e., greater than or equal to 3000), we will add the node to the newly created XmlDocument.

dv = New DataView(ds.Tables(0), "Product_price > = 3000", "Product_Name", DataViewRowState.CurrentRows)

Once the filtering process is complete, we will save the filtered XML data to a new file named "Result.XML" using the Save() method provided by the XmlDocument.


Full Source VB.NET
Imports System.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) Dim ds As New DataSet Dim dv As DataView ds.ReadXml(xmlFile) dv = New DataView(ds.Tables(0), "Product_price > = 3000", "Product_Name", DataViewRowState.CurrentRows) dv.ToTable().WriteXml("Result.xml") MsgBox("Done") End Sub End Class

Click here to download the input file product.xml

Conclusion

The provided solution demonstrates how to filter an XML file based on a specific criterion, in this case, the "Product_Price" field being greater than or equal to 3000. By using the capabilities of XmlDocument, we can efficiently extract the desired data and store it in a new XML file, facilitating further processing and analysis according to specific requirements.