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

黄舟
黄舟Original
2017-03-21 16:39:282717browse

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 f5d188ed2c074f8b944552db028f98a1 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 f5d188ed2c074f8b944552db028f98a1 elements (fae077d51b591786197c1ce2523c9adb and 20e0d2c31ebbe4ee5491ba472c0918be).

By using prefixes, we create two different types of f5d188ed2c074f8b944552db028f98a1 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:

d211f0a5ff2d5b27e2098f7409ee5eff
   5131fb50ac43ce34477ae02954db8af8African Coffee Tablef5a770fdb27d1c8ccb50245da14733bf
   b9784418d0fd3658f883ef7bdd1888468037265c5a838e5a28a65a2d8cfbd33e10
   61367a7e112dafa97c77aefb6b2c0f8b120ee55d0d45c3e1c817d93126a37f6bff6
008daa7d50ab7c214b59e96829b07c29

Instead of just using a prefix, we add an xmlns attribute to the f5d188ed2c074f8b944552db028f98a1 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