search
HomeBackend DevelopmentXML/RSS TutorialDetailed explanation of XML Namespaces (XML Namespaces) and sample code for node reading methods

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>

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

   <name>African Coffee Table</name>
   <width>80</width>
   <length>120</length>

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>

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>

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>

This XML document carries information about a piece of furniture:

<table>
   <name>African Coffee Table</name>
   <width>80</width>
   <length>120</length>
</table>

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"

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"

This XML document carries information in a table:

<tr> <td>Apples</td> <td>Bananas</td> </tr>

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)

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>

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

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>

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>

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


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
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
RSS & XML: Understanding the Dynamic Duo of Web ContentRSS & XML: Understanding the Dynamic Duo of Web ContentApr 19, 2025 am 12:03 AM

RSS and XML are tools for web content management. RSS is used to publish and subscribe to content, and XML is used to store and transfer data. They work with content publishing, subscriptions, and update push. Examples of usage include RSS publishing blog posts and XML storing book information.

RSS Documents: The Foundation of Web SyndicationRSS Documents: The Foundation of Web SyndicationApr 18, 2025 am 12:04 AM

RSS documents are XML-based structured files used to publish and subscribe to frequently updated content. Its main functions include: 1) automated content updates, 2) content aggregation, and 3) improving browsing efficiency. Through RSSfeed, users can subscribe and get the latest information from different sources in a timely manner.

Decoding RSS: The XML Structure of Content FeedsDecoding RSS: The XML Structure of Content FeedsApr 17, 2025 am 12:09 AM

The XML structure of RSS includes: 1. XML declaration and RSS version, 2. Channel (Channel), 3. Item. These parts form the basis of RSS files, allowing users to obtain and process content information by parsing XML data.

How to Parse and Utilize XML-Based RSS FeedsHow to Parse and Utilize XML-Based RSS FeedsApr 16, 2025 am 12:05 AM

RSSfeedsuseXMLtosyndicatecontent;parsingtheminvolvesloadingXML,navigatingitsstructure,andextractingdata.Applicationsincludebuildingnewsaggregatorsandtrackingpodcastepisodes.

RSS Documents: How They Deliver Your Favorite ContentRSS Documents: How They Deliver Your Favorite ContentApr 15, 2025 am 12:01 AM

RSS documents work by publishing content updates through XML files, and users subscribe and receive notifications through RSS readers. 1. Content publisher creates and updates RSS documents. 2. The RSS reader regularly accesses and parses XML files. 3. Users browse and read updated content. Example of usage: Subscribe to TechCrunch's RSS feed, just copy the link to the RSS reader.

Building Feeds with XML: A Hands-On Guide to RSSBuilding Feeds with XML: A Hands-On Guide to RSSApr 14, 2025 am 12:17 AM

The steps to build an RSSfeed using XML are as follows: 1. Create the root element and set the version; 2. Add the channel element and its basic information; 3. Add the entry element, including the title, link and description; 4. Convert the XML structure to a string and output it. With these steps, you can create a valid RSSfeed from scratch and enhance its functionality by adding additional elements such as release date and author information.

Creating RSS Documents: A Step-by-Step TutorialCreating RSS Documents: A Step-by-Step TutorialApr 13, 2025 am 12:10 AM

The steps to create an RSS document are as follows: 1. Write in XML format, with the root element, including the elements. 2. Add, etc. elements to describe channel information. 3. Add elements, each representing a content entry, including,,,,,,,,,,,. 4. Optionally add and elements to enrich the content. 5. Ensure the XML format is correct, use online tools to verify, optimize performance and keep content updated.

XML's Role in RSS: The Foundation of Syndicated ContentXML's Role in RSS: The Foundation of Syndicated ContentApr 12, 2025 am 12:17 AM

The core role of XML in RSS is to provide a standardized and flexible data format. 1. The structure and markup language characteristics of XML make it suitable for data exchange and storage. 2. RSS uses XML to create a standardized format to facilitate content sharing. 3. The application of XML in RSS includes elements that define feed content, such as title and release date. 4. Advantages include standardization and scalability, and challenges include document verbose and strict syntax requirements. 5. Best practices include validating XML validity, keeping it simple, using CDATA, and regularly updating.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.