Table of Contents
Naming conflict
Use prefixes to avoid naming conflicts
Using Namespaces
XML Namespace (xmlns) attribute
Uniform Resource Identifier (URI)
Default Namespaces
Home Backend Development XML/RSS Tutorial Detailed explanation of XML Namespaces (XML Namespaces) and sample code for node reading methods

Detailed explanation of XML Namespaces (XML Namespaces) and sample code for node reading methods

Mar 21, 2017 pm 04:39 PM

XML Namespace Provides a way to avoid element naming conflicts.

Naming conflict

In XML, element names are defined by developers. When two different documents use the same element name, a naming conflict occurs.

This XML document carries information in a table:

   <tr>
   <td>Apples</td>
   <td>Bananas</td>
   </tr>
Copy after login

This XML document carries information about a table (a piece of furniture):

   <name>African Coffee Table</name>
   <width>80</width>
   <length>120</length>
Copy after login

If these two XML documents are used together, and a naming conflict occurs because both documents contain

elements with different content and definitions.

The XML parser cannot determine how to handle such conflicts.

Use prefixes to avoid naming conflicts

This document carries information in a table:

   <h:tr>
   <h:td>Apples</h:td>
   <h:td>Bananas</h:td>
   </h:tr>
Copy after login

This XML document carries information about a piece of furniture:

   <f:name>African Coffee Table</f:name>
   <f:width>80</f:width>
   <f:length>120</f:length>
Copy after login

Now, the naming conflict no longer exists because both documents use different names for their

elements ( and ).

By using prefixes, we create two different types of

elements.

Using Namespaces

This XML document carries information in a table:


   <h:tr>
   <h:td>Apples</h:td>
   <h:td>Bananas</h:td>
   </h:tr>
Copy after login

This XML document carries information about a piece of furniture:


   <f:name>African Coffee Table</f:name>
   <f:width>80</f:width>
   <f:length>120</f:length>
Copy after login

Instead of just using a prefix, we add an xmlns attribute to the

tag, which gives the prefix a qualified name associated with a namespace.

XML Namespace (xmlns) attribute

The XML namespace attribute is placed in the opening tag of the element and uses the following syntax:

xmlns:namespace-prefix="namespaceURI"
Copy after login

When the namespace is defined When in the opening tag of an element, all child elements with the same prefix are associated with the same namespace.

Note: The address used to identify the namespace will not be used by the parser to find information. Its only purpose is to give the namespace a unique name. However, many companies often use namespaces as pointers to actual existing web pages that contain information about the namespace.

Uniform Resource Identifier (URI)

Uniform Resource Identifier is a string of characters that can identify Internet resources. The most commonly used URI is the Uniform Resource Locator (URL) used to designate an Internet domain name address. Another less commonly used URI is Uniform Resource Naming (URN). In our example, we just use the URL.

Default Namespaces

Defining a default namespace for an element saves us the work of using prefixes in all child elements.

Please use the following syntax:

xmlns="namespaceURI"
Copy after login

This XML document carries information in a table:

<tr> <td>Apples</td> <td>Bananas</td> </tr>
Copy after login

This XML document carries information about a piece of furniture:


   <name>African Coffee Table</name>
   <width>80</width>
   <length>120</length>
(转原文http://www.cnblogs.com/mgen/archive/2011/05/24/2056025.html)
Copy after login

As we all know, XmlDocument can perform XPathquery, but in fact the XPath query mentioned here is limited to XML without namespace (no xmlns attribute), once When encountering XML with namespace, the corresponding XPath query will have no results.

For example, the following XML

<a xmlns="mgen.cnblogs.com">
    <b>ccc</b>
</a>
Copy after login

XPath query /a/b will return null, and if there is no xmlns, node b will be returned.

If the XPath expression does not include a prefix, it is assumed that the namespace URI is the empty namespace. 
If your XML includes a default namespace, you must still add a prefix and namespace URI to the XmlNamespaceManager; 
otherwise, you will not get any nodes selected
Copy after login

means that if the XPathexpression is not prefixed (for example, the prefix in a:b is a), then the namespace URI of the queried node (note that the attribute can also be a node) is Should be empty (also the default value), otherwise XPath will not return results.

In the above XML, because nodes a and b have namespace values, naturally the XPath query will have no results.

(The above English also mentioned that if the node has a default namespace, then you have to manually add the prefix and namespace value to the XmlNamespaceManager, which will be discussed later)

Before looking at the solution, First of all, you need to be able to identify the XML namespace. Of course, it is still very easy to identify the XML namespace value. Refer to the following XML (this XML will also be used in the later program)

<?xmlversion="1.0" encoding="utf-8"?>
<rootxmlns="dotnet" xmlns:w="wpf">
  <a>data in a</a>                
  <w:b>data in b</w:b>         
  <cxmlns="silverlight">
    <w:d>                             
      <e>data in e</e>              
    </w:d>
  </c>
</root>
Copy after login

The namespace of all its XML nodes is as follows Shown:

<?xmlversion="1.0" encoding="utf-8"?>
<rootxmlns="dotnet" xmlns:w="wpf">
  <!-- xmlns: dotnet -->
  <a>data in a</a>
  <!-- xmlns: dotnet -->
  <w:b>data in b</w:b>
  <!-- xmlns: wpf -->
  <cxmlns="silverlight">
    <!-- xmlns: silverlight -->
    <w:d>
      <!-- xmlns: wpf -->
      <e>data in e</e>
      <!-- xmlns: silverlight -->
    </w:d>
  </c>
</root>
Copy after login

If there is no problem in identifying the XML namespace, then the subsequent operations are quite simple. You need to remember: In XmlDocument When using XPath to query a node, as long as its namespace value is not null, you must give it a prefix . Use this prefix to represent the namespace value of this node! These prefixes are added through the XmlNamespaceManager class. When using, just pass the XmlNamespaceManager into SelectNodes or SelectSingleNode. This is why it is said above that "If the node has a default namespace, then you have to manually add the prefix and namespace value to the XmlNamespaceManager".

另外构造一个XmlNamespaceManager需要XmlNameTable对象,这个对象可以从XmlDocument.NameTable和XmlReader.NameTable属性中得到。

下面我们步入代码,比如说查询上面XML中的节点e,分析位置节点e位于:root->c->d->e,然后将所需命名空间值加入到 XmlNamespaceManager中(前缀名称无所谓,只要在XPath一致即可),查询即可成功,如下代码:

   /*
              * 假设上面XML文件在C:\a.txt中
              * 下面代码会查询目标节点e,并输出数据:data in e
              * */
 
            var xmlDoc =newXmlDocument();
            xmlDoc.Load(@"C:\a.txt");
 
            //加入命名空间和前缀
            var xmlnsm =newXmlNamespaceManager(xmlDoc.NameTable);
            xmlnsm.AddNamespace("d", "dotnet");
            xmlnsm.AddNamespace("s", "silverlight");
            xmlnsm.AddNamespace("w", "wpf");
 
            var node = xmlDoc.SelectSingleNode("/d:root/s:c/w:d/s:e", xmlnsm);
            Console.WriteLine(node.InnerText);
 
            //输出:data in e
Copy after login


The above is the detailed content of Detailed explanation of XML Namespaces (XML Namespaces) and sample code for node reading methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Convert XML data to CSV format in Python Convert XML data to CSV format in Python Aug 11, 2023 pm 07:41 PM

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Solve PHP error: The specified namespace class was not found Solve PHP error: The specified namespace class was not found Aug 18, 2023 pm 11:28 PM

Solve PHP error: The specified namespace class was not found. When developing using PHP, we often encounter various error messages. One of the common errors is "The specified namespace class was not found". This error is usually caused by the imported class file not being properly namespace referenced. This article explains how to solve this problem and provides some code examples. First, let’s take a look at an example of a common error message: Fatalerror:UncaughtError:C

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

Using Python to implement data verification in XML Using Python to implement data verification in XML Aug 10, 2023 pm 01:37 PM

Using Python to implement data validation in XML Introduction: In real life, we often deal with a variety of data, among which XML (Extensible Markup Language) is a commonly used data format. XML has good readability and scalability, and is widely used in various fields, such as data exchange, configuration files, etc. When processing XML data, we often need to verify the data to ensure the integrity and correctness of the data. This article will introduce how to use Python to implement data verification in XML and give the corresponding

How to use PHP functions to process XML data? How to use PHP functions to process XML data? May 05, 2024 am 09:15 AM

Use PHPXML functions to process XML data: Parse XML data: simplexml_load_file() and simplexml_load_string() load XML files or strings. Access XML data: Use the properties and methods of the SimpleXML object to obtain element names, attribute values, and subelements. Modify XML data: add new elements and attributes using the addChild() and addAttribute() methods. Serialized XML data: The asXML() method converts a SimpleXML object into an XML string. Practical example: parse product feed XML, extract product information, transform and store it into a database.

Convert POJO to XML using Jackson library in Java? Convert POJO to XML using Jackson library in Java? Sep 18, 2023 pm 02:21 PM

Jackson is a Java-based library that is useful for converting Java objects to JSON and JSON to Java objects. JacksonAPI is faster than other APIs, requires less memory area, and is suitable for large objects. We use the writeValueAsString() method of the XmlMapper class to convert the POJO to XML format, and the corresponding POJO instance needs to be passed as a parameter to this method. Syntax publicStringwriteValueAsString(Objectvalue)throwsJsonProcessingExceptionExampleimp

C++ syntax error: undefined namespace used, how to deal with it? C++ syntax error: undefined namespace used, how to deal with it? Aug 21, 2023 pm 09:49 PM

C++ is a widely used high-level programming language. It has high flexibility and scalability, but it also requires developers to strictly master its grammatical rules to avoid errors. One of the common errors is "use of undefined namespace". This article explains what this error means, why it occurs, and how to fix it. 1. What is the use of undefined namespace? In C++, namespaces are a way of organizing reusable code in order to keep it modular and readable. You can use namespaces to make functions with the same name

See all articles