SoFunction
Updated on 2025-03-07

c# Read xml example through xpath


using System;
using ;
using ;
using ;
using ;
using ;

namespace XmlProcessTest
{
    public class Program
    {
        /// <summary>
/// Load XML file
        /// </summary>
/// <param name="xmlFilePath">XML file path</param>
        /// <returns></returns>
        public static XmlDocument LoadXmlDoc(string xmlFilePath)
        {
            var xmlDoc = new XmlDocument();
            (xmlFilePath);

            return xmlDoc;
        }

        /// <summary>
/// Get the XML node list based on the specified XPath expression
        /// </summary>
        /// <param name="xmlDoc"></param>
        /// <param name="xpathExpr"></param>
        /// <returns></returns>
        public static XmlNodeList GetXmlNodes(XmlDocument xmlDoc, string xpathExpr)
        {
            if (xmlDoc == null)
                return null;

            return (xpathExpr);
        }

        public static string GetXmlNodeInfo(XmlNode node, string type="xml")
        {
            if (node == null)
                return "Empty node or error node";

            string xmlNodeInfo = null;
            switch (type)
            {
                case "text":
                    xmlNodeInfo = ;
                    break;
                default:
                    xmlNodeInfo = ;
                    break;
            }

            return xmlNodeInfo;
        }

        public static void Main(string[] args)
        {
var xmlDoc = LoadXmlDoc(@"Your file path");

var rootExpr = "/bookstore";   //  XPath expression corresponding to the root node
            var rootNode = GetXmlNodes(xmlDoc, rootExpr);   //
("XPath expression is /bookstore, and all child nodes XML content of the root node bookstore is as follows: ");
            (GetXmlNodeInfo(rootNode[0]));

            ();

var allBooksExpr = "/bookstore/book"; // All children of the child elements of the root node bookstore
            var bookNodes = GetXmlNodes(xmlDoc, allBooksExpr);
("XPath expression is bookstore/book, and the book nodes have a total of: " + );

            ();

var anyBookExpr = "//book"; // Select all book child elements regardless of their location in the document
            var anyBookNodes = GetXmlNodes(xmlDoc, anyBookExpr);
("XPath expression is //book, and the book nodes have a total of: " + );
            (anyBookNodes[0].InnerXml);
            (anyBookNodes[0].OuterXml);

            ();

var categoryExpr = "//@category";   // Select all attributes named category
            var allCategoryNodes = GetXmlNodes(xmlDoc, categoryExpr);
("XPath expression is //@category, and the category nodes have a total of: " + );
            (allCategoryNodes[0].InnerText);
            (allCategoryNodes[0].InnerXml);

            ();

var titleWithLangExpr = "//title[@lang]";   // Select all title nodes with lang attributes
            var titleWithLangNodes = GetXmlNodes(xmlDoc, titleWithLangExpr);
("XPath expression is //title[@lang], and the title nodes with lang attributes have a total of: " + );
            (GetXmlNodeInfo(titleWithLangNodes[0]));

var englishTitleExpr = "//title[@lang='en']";   // Select all title nodes with en attribute value
            var englishTitleNodes = GetXmlNodes(xmlDoc, englishTitleExpr);
("XPath expression is //title[@lang='en'], and the title nodes with the lang attribute value en have a total of: " + );
            (GetXmlNodeInfo(englishTitleNodes[0]));

            ();

// XPath query using index
var indexExpr = "/bookstore/book[1]";   // Take the first book element of the bookstore child element
            var firstBookNode = GetXmlNodes(xmlDoc, indexExpr);
("XPath expression is /bookstore/book[1], and the number of nodes is: " + );
            (GetXmlNodeInfo(firstBookNode[0]));

            ();

var indexExpr2 = "/bookstore/book[last()]"; // Take the last book element of the bookstore child element
            var lastBookNode = GetXmlNodes(xmlDoc, indexExpr2);
("XPath expression is /bookstore/book[last()], and the number of nodes is: " + );
            (GetXmlNodeInfo(lastBookNode[0]));

            ();

var indexExpr3 = "/bookstore/book[last()-1]"; // Take the penultimate book element of the bookstore child element
            var nextByLastBookNode = GetXmlNodes(xmlDoc, indexExpr3);
("XPath expression is /bookstore/book[last()-1], and the number of nodes is: " + );
            (GetXmlNodeInfo(nextByLastBookNode[0]));

            ();

var indexExpr4 = "/bookstore/book[position()<3]"; // Take the first two book child elements of the bookstore
            var firstTwoBookNodes = GetXmlNodes(xmlDoc, indexExpr4);
("XPath expression is /bookstore/book[position()<3], and the number of nodes is: " + );
            (GetXmlNodeInfo(firstTwoBookNodes[0]));

            ();

// XPath expression with attribute value filtering conditions
var fileterExpr = "/bookstore/book[price>35.00]";   // Select all book elements with price attribute values ​​greater than 35.00 in the bookstore
            var bookGt35Nodes = GetXmlNodes(xmlDoc, fileterExpr);
("XPath expression is /bookstore/book[price>35.00], and the number of nodes is: " + );
            (GetXmlNodeInfo(bookGt35Nodes[0]));

// Wildcard
// @*                                                             �
// node()                                                                                                                             �
// /bookstore/*   Select all child elements of the bookstore element
// //*
//title[@*]
            var allTitleWithAttrExpr = "//title[@*]";
            var allTitleWithAttrNodes = GetXmlNodes(xmlDoc, allTitleWithAttrExpr);
("XPath expression is title[@*], and the number of nodes is: " + );
            (GetXmlNodeInfo(allTitleWithAttrNodes[0]));

            ();

// |
            var titleAndPriceExpr = "//book/title | //book/price";
            var titleAndPriceNodes = GetXmlNodes(xmlDoc, titleAndPriceExpr);
("XPath expression is //book/title | //book/price, the number of nodes is: " + );
            (GetXmlNodeInfo(titleAndPriceNodes[0]));

// text() select text
            var titleTextExpr = "//title/text()";
            var titleTextNodes = GetXmlNodes(xmlDoc, titleTextExpr);
("XPath expression is //title/text(), and the number of nodes is: " + );
(titleTextNodes[0].Value); // The value of the text node

            ();
        }
    }
}