SoFunction
Updated on 2025-04-10

How to access XML files using XmlDocument in C#

1. Detailed introduction to XML files

XML files can be extended markup language (eXtensible Markup Language) files. They are files in plain text formats that describe and store data to make them structural.

The following is a detailed introduction to XML files:

1. Features of XML files

  1. Scalability: XML allows users to define their own tags as needed, which makes XML very flexible and able to adapt to various complex data structures.
  2. Platform irrelevance: XML files are plain text files that can be read and parsed on any platform that supports text processing without worrying about platform differences.
  3. Self-descriptive: The tags in the XML file themselves contain the meaning and structure information of the data, which makes the XML file easy to understand and maintain.
  4. Easy to verify: XML files can be verified using XML schema (XMLSchema) to ensure the consistency and integrity of the data.

2. The purpose of XML files

  1. Data exchange: XML files can be used as a common format for exchanging data between different systems and applications, achieving seamless data connection.
  2. Document storage: XML files can be used to store structured documents, such as books, articles and reports, to facilitate the organization and management of data.
  3. Configuration Management: Many applications and systems use XML files to store configuration information, such as database connection information, system parameters, etc.
  4. Internet applications: In the fields of Web services, SOA (service-oriented architecture), XML files are widely used in data exchange and transmission.

3. XML file format

The format of an XML file generally includes the following parts:

  1. Statement section: Includes XML version number and character set declaration, such as "<?xml version="1.0" encoding="UTF-8"?>”。
  2. Root element: All elements in an XML file must be included in a root element, which is the highest level element of the XML file.
  3. Elements and properties: Elements in the XML file contain a start tag, an end tag and intermediate data. An element may also contain attributes that describe the characteristics of an element.

4. Examples of XML files

Here is a simple XML file example:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book>
    <title lang="en">Harry Potter</title>
    <author>. Rowling</author>
    <year>1997</year>
    <price>29.99</price>
  </book>
  <book>
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

In this example,<bookstore>"is the root element, containing two"<book>"Elements, each"<book>"The element has a"id"Properties (although not directly displayed in the example, they can be added in actual use) and "<title>”、“<author>”、“<year>"and"<price>”Sub-element.

5. Parse and processing of XML files

In order to use the data in the XML file, the XML file needs to be parsed and processed. Common XML parsing and processing methods are:

  1. DOM (Document Object Model) Analysis: Based on the analysis method of tree structure, parsing the XML file into a tree structure, and then the node operation method can be used to access and manipulate the data in the XML file.
  2. SAX (Simple API for XML) parsing: Based on event-driven parsing method, the XML file is parsed into a series of events, and the corresponding event processor is triggered during the parsing process to handle these events.
  3. JAXB(Java Architecture for XML Binding): A technique for converting XML files into Java objects. Using JAXB processing, you can parse XML files into Java objects, and then directly operate Java objects to access and process data in XML files.

6. XML file opening and editing tools

XML files can be opened, viewed and edited using a variety of software and tools, including but not limited to:

  • Notepad: The text editor that comes with Windows system can directly open XML files in plain text and display their contents.
  • Third-party text editor: Such as Notepad++, Sublime Text, Visual Studio Code, etc. These editors usually provide syntax highlighting, code folding, multi-document editing and other functions, making reading and editing of XML files more convenient.
  • Modern browser: For example, Google Chrome, Mozilla Firefox, Microsoft Edge, etc., all have built-in XML parsers, allowing users to open XML files directly in the browser.
  • Specialized XML editor: Such as XMLSpy, Oxygen XML Editor, etc. These editors provide richer functions and more friendly interfaces, and usually support syntax highlighting, automatic completion, syntax checking, XPath query and other functions.
  • Integrated Development Environment (IDE): Such as Eclipse, IntelliJ IDEA, Visual Studio, etc. These IDEs also support the editing and debugging of XML files, and provide powerful code editing, debugging and project management functions.

To sum up, XML files are a powerful and flexible data description and storage method, which are widely used in various fields.

By choosing the right tools and parsing methods, data in XML files can be processed and used efficiently.

2. Use XmlDocument in C# to add, delete, modify and search XML files

In C#, useXmlDocumentClasses can easily access and modify XML files.

Here's how to use itXmlDocumentPerform detailed steps of adding (adding nodes), deleting (deleting nodes), modifying (modifying node content), and querying (querying nodes).

1. Load XML file

First, you need to load the XML file toXmlDocumentin object.

XmlDocument xmlDoc = new XmlDocument();
("path_to_your_file.xml");

2. Query node

useSelectSingleNodeorSelectNodesMethods can query nodes based on XPath expression.

// Query the first <person> nodeXmlNode personNode = ("/root/person");

// Query all <person> nodesXmlNodeList personNodes = ("/root/person");

3. Modify the node content

After finding the node to be modified, you can set it directlyInnerTextorInnerXmlproperty.

// Modify the text of the <name> child node of the first <person> nodeXmlNode nameNode = personNode["name"];
 = "New Name";

4. Add nodes

useCreateElementandAppendChildorInsertBeforeAdd new nodes, etc.

// Create a new <person> nodeXmlNode newPersonNode = ("person");

// Create <name> and <age> child nodes and set their textXmlNode newNameNode = ("name");
 = "Alice Johnson";

XmlNode newAgeNode = ("age");
 = "28";

// Add child nodes to new <person> nodes(newNameNode);
(newAgeNode);

// Add a new <person> node to the <root> node(newPersonNode);

5. Delete nodes

useRemoveChildMethods can delete nodes.

// Suppose you want to delete the first <person> node(personNode);

6. Save XML files

After modifying the XML document, it needs to be saved back to the file.

("path_to_your_file.xml");

7. Things to note

  • Before making any modifications, it is best to check whether the node exists to avoid empty reference exceptions.
  • XPath expressions are used to locate nodes in XML documents and are a powerful tool for querying XML documents.
  • You can call before saving the XML fileXmlDocumentofValidateMethod (if XML Schema is defined) to verify that the document complies with the schema.
  • If the XML file is large, useXmlDocumentIt may consume more memory. In this case, consider usingXmlReaderPerform line-by-line reading and processing.

Summarize

The above is usedXmlDocumentBasic ways to access and modify XML files in C#. Depending on the specific needs, more complex operations can be performed, such as adding properties, processing namespaces, etc.