活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

深入浅出XML DOM属性获取技术从基础语法到高级应用全面解析开发者如何高效操作文档节点解决数据访问难题

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-4 00:40:06 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

XML(可扩展标记语言)作为一种通用的数据交换格式,在现代软件开发中扮演着至关重要的角色。无论是配置文件、数据传输还是文档存储,XML都提供了一种结构化、自描述的方式来表示信息。而XML DOM(文档对象模型)则是处理XML文档的标准接口,它将XML文档表示为一个树形结构,允许开发者通过编程语言动态访问和修改文档的内容、结构和样式。

掌握XML DOM属性获取技术对于开发者来说至关重要,它不仅能够帮助我们高效地操作文档节点,还能解决复杂的数据访问难题。本文将从基础语法到高级应用,全面解析XML DOM属性获取技术,帮助开发者深入理解并灵活运用这一技术。

XML DOM基础概念

什么是XML DOM

XML DOM(Document Object Model)是一个与平台和语言无关的接口,它允许程序和脚本动态地访问和更新XML文档的内容、结构和样式。DOM将XML文档表示为一个树形结构,其中每个节点代表文档中的一个部分(如元素、属性、文本等)。

DOM树结构

在DOM中,XML文档被表示为一个层次结构的树,包含以下几种主要节点类型:

1. 文档节点(Document):整个XML文档的根节点
2. 元素节点(Element):表示XML元素
3. 属性节点(Attribute):表示元素的属性
4. 文本节点(Text):表示元素或属性中的文本内容
5. 注释节点(Comment):表示XML注释
6. 处理指令节点(Processing Instruction):表示XML处理指令

例如,对于以下XML文档:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <bookstore>
  3.   <book category="fiction">
  4.     <title lang="en">Harry Potter</title>
  5.     <author>J.K. Rowling</author>
  6.     <year>2005</year>
  7.     <price>29.99</price>
  8.   </book>
  9.   <book category="children">
  10.     <title lang="en">The Wonderful Wizard of Oz</title>
  11.     <author>L. Frank Baum</author>
  12.     <year>1900</year>
  13.     <price>15.99</price>
  14.   </book>
  15. </bookstore>
复制代码

其对应的DOM树结构如下:
  1. Document
  2. └── Element: bookstore
  3.       ├── Element: book (attribute: category="fiction")
  4.       │    ├── Element: title (attribute: lang="en")
  5.       │    │    └── Text: Harry Potter
  6.       │    ├── Element: author
  7.       │    │    └── Text: J.K. Rowling
  8.       │    ├── Element: year
  9.       │    │    └── Text: 2005
  10.       │    └── Element: price
  11.       │         └── Text: 29.99
  12.       └── Element: book (attribute: category="children")
  13.            ├── Element: title (attribute: lang="en")
  14.            │    └── Text: The Wonderful Wizard of Oz
  15.            ├── Element: author
  16.            │    └── Text: L. Frank Baum
  17.            ├── Element: year
  18.            │    └── Text: 1900
  19.            └── Element: price
  20.                 └── Text: 15.99
复制代码

DOM接口的基本组成

DOM接口由多个部分组成,主要包括:

1. Core DOM:定义了所有文档类型共用的基本接口
2. XML DOM:定义了专门针对XML文档的接口
3. HTML DOM:定义了专门针对HTML文档的接口

在本文中,我们主要关注XML DOM,它提供了处理XML文档的特定方法和属性。

DOM属性获取的基础语法

获取DOM对象

在开始操作XML DOM之前,首先需要获取DOM对象。不同的编程语言有不同的方式来加载XML文档并创建DOM对象。以下是几种常见语言的示例:
  1. // 在浏览器环境中
  2. let parser = new DOMParser();
  3. let xmlDoc = parser.parseFromString(xmlString, "text/xml");
  4. // 或者加载XML文件
  5. let xhttp = new XMLHttpRequest();
  6. xhttp.onreadystatechange = function() {
  7.   if (this.readyState == 4 && this.status == 200) {
  8.     let xmlDoc = this.responseXML;
  9.     // 操作DOM
  10.   }
  11. };
  12. xhttp.open("GET", "books.xml", true);
  13. xhttp.send();
复制代码
  1. import javax.xml.parsers.DocumentBuilder;
  2. import javax.xml.parsers.DocumentBuilderFactory;
  3. import org.w3c.dom.Document;
  4. import java.io.File;
  5. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  6. DocumentBuilder builder = factory.newDocumentBuilder();
  7. Document document = builder.parse(new File("books.xml"));
复制代码
  1. from xml.dom.minidom import parse
  2. # 解析XML文件
  3. dom = parse("books.xml")
  4. # 或者从字符串解析
  5. from xml.dom.minidom import parseString
  6. dom = parseString(xmlString)
复制代码
  1. using System.Xml;
  2. // 加载XML文件
  3. XmlDocument xmlDoc = new XmlDocument();
  4. xmlDoc.Load("books.xml");
  5. // 或者从字符串加载
  6. xmlDoc.LoadXml(xmlString);
复制代码

基本属性访问

一旦获得了DOM对象,就可以开始访问和操作文档的属性。以下是一些基本的属性访问方法:
  1. // JavaScript
  2. let rootElement = xmlDoc.documentElement;
复制代码
  1. // Java
  2. Element rootElement = document.getDocumentElement();
复制代码
  1. # Python
  2. root_element = dom.documentElement
复制代码
  1. // C#
  2. XmlElement rootElement = xmlDoc.DocumentElement;
复制代码
  1. // JavaScript
  2. let bookElement = xmlDoc.getElementsByTagName("book")[0];
  3. let category = bookElement.getAttribute("category");
复制代码
  1. // Java
  2. NodeList bookList = document.getElementsByTagName("book");
  3. Element bookElement = (Element) bookList.item(0);
  4. String category = bookElement.getAttribute("category");
复制代码
  1. # Python
  2. book_elements = dom.getElementsByTagName("book")
  3. book_element = book_elements[0]
  4. category = book_element.getAttribute("category")
复制代码
  1. // C#
  2. XmlNodeList bookList = xmlDoc.GetElementsByTagName("book");
  3. XmlElement bookElement = (XmlElement)bookList[0];
  4. string category = bookElement.GetAttribute("category");
复制代码
  1. // JavaScript
  2. let bookElement = xmlDoc.getElementsByTagName("book")[0];
  3. if (bookElement.hasAttribute("category")) {
  4.   console.log("Category attribute exists");
  5. }
复制代码
  1. // Java
  2. Element bookElement = (Element) document.getElementsByTagName("book").item(0);
  3. if (bookElement.hasAttribute("category")) {
  4.   System.out.println("Category attribute exists");
  5. }
复制代码
  1. # Python
  2. book_element = dom.getElementsByTagName("book")[0]
  3. if book_element.hasAttribute("category"):
  4.     print("Category attribute exists")
复制代码
  1. // C#
  2. XmlElement bookElement = (XmlElement)xmlDoc.GetElementsByTagName("book")[0];
  3. if (bookElement.HasAttribute("category"))
  4. {
  5.     Console.WriteLine("Category attribute exists");
  6. }
复制代码

常用DOM属性和方法

获取属性值

getAttribute方法是最常用的获取属性值的方法,它接受属性名作为参数,返回对应的属性值。
  1. // JavaScript
  2. let titleElement = xmlDoc.getElementsByTagName("title")[0];
  3. let lang = titleElement.getAttribute("lang");
  4. console.log(lang); // 输出: en
复制代码
  1. // Java
  2. Element titleElement = (Element) document.getElementsByTagName("title").item(0);
  3. String lang = titleElement.getAttribute("lang");
  4. System.out.println(lang); // 输出: en
复制代码
  1. # Python
  2. title_element = dom.getElementsByTagName("title")[0]
  3. lang = title_element.getAttribute("lang")
  4. print(lang)  # 输出: en
复制代码
  1. // C#
  2. XmlElement titleElement = (XmlElement)xmlDoc.GetElementsByTagName("title")[0];
  3. string lang = titleElement.GetAttribute("lang");
  4. Console.WriteLine(lang); // 输出: en
复制代码

getAttributeNode方法返回一个属性节点,而不是直接返回属性值。这在需要进一步操作属性节点时很有用。
  1. // JavaScript
  2. let titleElement = xmlDoc.getElementsByTagName("title")[0];
  3. let langAttr = titleElement.getAttributeNode("lang");
  4. console.log(langAttr.value); // 输出: en
  5. console.log(langAttr.name);  // 输出: lang
复制代码
  1. // Java
  2. Element titleElement = (Element) document.getElementsByTagName("title").item(0);
  3. Attr langAttr = titleElement.getAttributeNode("lang");
  4. System.out.println(langAttr.getValue()); // 输出: en
  5. System.out.println(langAttr.getName());  // 输出: lang
复制代码
  1. # Python
  2. title_element = dom.getElementsByTagName("title")[0]
  3. lang_attr = title_element.getAttributeNode("lang")
  4. print(lang_attr.value)  # 输出: en
  5. print(lang_attr.name)   # 输出: lang
复制代码
  1. // C#
  2. XmlElement titleElement = (XmlElement)xmlDoc.GetElementsByTagName("title")[0];
  3. XmlAttribute langAttr = titleElement.GetAttributeNode("lang");
  4. Console.WriteLine(langAttr.Value); // 输出: en
  5. Console.WriteLine(langAttr.Name);  // 输出: lang
复制代码

attributes属性返回一个包含元素所有属性的NamedNodeMap或类似集合,可以通过属性名或索引访问。
  1. // JavaScript
  2. let titleElement = xmlDoc.getElementsByTagName("title")[0];
  3. let attributes = titleElement.attributes;
  4. // 通过属性名访问
  5. let lang = attributes.getNamedItem("lang").value;
  6. console.log(lang); // 输出: en
  7. // 遍历所有属性
  8. for (let i = 0; i < attributes.length; i++) {
  9.   let attr = attributes[i];
  10.   console.log(attr.name + ": " + attr.value);
  11. }
复制代码
  1. // Java
  2. Element titleElement = (Element) document.getElementsByTagName("title").item(0);
  3. NamedNodeMap attributes = titleElement.getAttributes();
  4. // 通过属性名访问
  5. Node langAttr = attributes.getNamedItem("lang");
  6. System.out.println(langAttr.getNodeValue()); // 输出: en
  7. // 遍历所有属性
  8. for (int i = 0; i < attributes.getLength(); i++) {
  9.   Node attr = attributes.item(i);
  10.   System.out.println(attr.getNodeName() + ": " + attr.getNodeValue());
  11. }
复制代码
  1. # Python
  2. title_element = dom.getElementsByTagName("title")[0]
  3. attributes = title_element.attributes
  4. # 通过属性名访问
  5. lang_attr = attributes.getNamedItem("lang")
  6. print(lang_attr.value)  # 输出: en
  7. # 遍历所有属性
  8. for i in range(attributes.length):
  9.     attr = attributes.item(i)
  10.     print(f"{attr.name}: {attr.value}")
复制代码
  1. // C#
  2. XmlElement titleElement = (XmlElement)xmlDoc.GetElementsByTagName("title")[0];
  3. XmlAttributeCollection attributes = titleElement.Attributes;
  4. // 通过属性名访问
  5. XmlAttribute langAttr = attributes["lang"];
  6. Console.WriteLine(langAttr.Value); // 输出: en
  7. // 遍历所有属性
  8. foreach (XmlAttribute attr in attributes)
  9. {
  10.     Console.WriteLine(attr.Name + ": " + attr.Value);
  11. }
复制代码

设置属性值

setAttribute方法用于设置元素的属性值,如果属性不存在则创建该属性。
  1. // JavaScript
  2. let bookElement = xmlDoc.getElementsByTagName("book")[0];
  3. bookElement.setAttribute("category", "fantasy");
复制代码
  1. // Java
  2. Element bookElement = (Element) document.getElementsByTagName("book").item(0);
  3. bookElement.setAttribute("category", "fantasy");
复制代码
  1. # Python
  2. book_element = dom.getElementsByTagName("book")[0]
  3. book_element.setAttribute("category", "fantasy")
复制代码
  1. // C#
  2. XmlElement bookElement = (XmlElement)xmlDoc.GetElementsByTagName("book")[0];
  3. bookElement.SetAttribute("category", "fantasy");
复制代码

setAttributeNode方法用于添加一个新的属性节点到元素上。
  1. // JavaScript
  2. let bookElement = xmlDoc.getElementsByTagName("book")[0];
  3. let newAttr = xmlDoc.createAttribute("id");
  4. newAttr.value = "b001";
  5. bookElement.setAttributeNode(newAttr);
复制代码
  1. // Java
  2. Element bookElement = (Element) document.getElementsByTagName("book").item(0);
  3. Attr newAttr = document.createAttribute("id");
  4. newAttr.setValue("b001");
  5. bookElement.setAttributeNode(newAttr);
复制代码
  1. # Python
  2. book_element = dom.getElementsByTagName("book")[0]
  3. new_attr = dom.createAttribute("id")
  4. new_attr.value = "b001"
  5. book_element.setAttributeNode(new_attr)
复制代码
  1. // C#
  2. XmlElement bookElement = (XmlElement)xmlDoc.GetElementsByTagName("book")[0];
  3. XmlAttribute newAttr = xmlDoc.CreateAttribute("id");
  4. newAttr.Value = "b001";
  5. bookElement.SetAttributeNode(newAttr);
复制代码

删除属性

removeAttribute方法用于删除元素的指定属性。
  1. // JavaScript
  2. let bookElement = xmlDoc.getElementsByTagName("book")[0];
  3. bookElement.removeAttribute("category");
复制代码
  1. // Java
  2. Element bookElement = (Element) document.getElementsByTagName("book").item(0);
  3. bookElement.removeAttribute("category");
复制代码
  1. # Python
  2. book_element = dom.getElementsByTagName("book")[0]
  3. book_element.removeAttribute("category")
复制代码
  1. // C#
  2. XmlElement bookElement = (XmlElement)xmlDoc.GetElementsByTagName("book")[0];
  3. bookElement.RemoveAttribute("category");
复制代码

removeAttributeNode方法用于删除指定的属性节点,并返回被删除的节点。
  1. // JavaScript
  2. let bookElement = xmlDoc.getElementsByTagName("book")[0];
  3. let categoryAttr = bookElement.getAttributeNode("category");
  4. let removedAttr = bookElement.removeAttributeNode(categoryAttr);
  5. console.log("Removed attribute: " + removedAttr.name);
复制代码
  1. // Java
  2. Element bookElement = (Element) document.getElementsByTagName("book").item(0);
  3. Attr categoryAttr = bookElement.getAttributeNode("category");
  4. Attr removedAttr = bookElement.removeAttributeNode(categoryAttr);
  5. System.out.println("Removed attribute: " + removedAttr.getName());
复制代码
  1. # Python
  2. book_element = dom.getElementsByTagName("book")[0]
  3. category_attr = book_element.getAttributeNode("category")
  4. removed_attr = book_element.removeAttributeNode(category_attr)
  5. print(f"Removed attribute: {removed_attr.name}")
复制代码
  1. // C#
  2. XmlElement bookElement = (XmlElement)xmlDoc.GetElementsByTagName("book")[0];
  3. XmlAttribute categoryAttr = bookElement.GetAttributeNode("category");
  4. XmlAttribute removedAttr = bookElement.RemoveAttributeNode(categoryAttr);
  5. Console.WriteLine("Removed attribute: " + removedAttr.Name);
复制代码

节点遍历技术

父子节点访问
  1. // JavaScript
  2. let titleElement = xmlDoc.getElementsByTagName("title")[0];
  3. let parentElement = titleElement.parentNode;
  4. console.log(parentElement.tagName); // 输出: book
复制代码
  1. // Java
  2. Element titleElement = (Element) document.getElementsByTagName("title").item(0);
  3. Node parentElement = titleElement.getParentNode();
  4. System.out.println(parentElement.getNodeName()); // 输出: book
复制代码
  1. # Python
  2. title_element = dom.getElementsByTagName("title")[0]
  3. parent_element = title_element.parentNode
  4. print(parent_element.tagName)  # 输出: book
复制代码
  1. // C#
  2. XmlElement titleElement = (XmlElement)xmlDoc.GetElementsByTagName("title")[0];
  3. XmlNode parentElement = titleElement.ParentNode;
  4. Console.WriteLine(parentElement.Name); // 输出: book
复制代码
  1. // JavaScript
  2. let bookElement = xmlDoc.getElementsByTagName("book")[0];
  3. let childNodes = bookElement.childNodes;
  4. // 遍历子节点
  5. for (let i = 0; i < childNodes.length; i++) {
  6.   let node = childNodes[i];
  7.   if (node.nodeType === Node.ELEMENT_NODE) {
  8.     console.log(node.tagName + ": " + node.textContent);
  9.   }
  10. }
复制代码
  1. // Java
  2. Element bookElement = (Element) document.getElementsByTagName("book").item(0);
  3. NodeList childNodes = bookElement.getChildNodes();
  4. // 遍历子节点
  5. for (int i = 0; i < childNodes.getLength(); i++) {
  6.   Node node = childNodes.item(i);
  7.   if (node.getNodeType() == Node.ELEMENT_NODE) {
  8.     System.out.println(node.getNodeName() + ": " + node.getTextContent());
  9.   }
  10. }
复制代码
  1. # Python
  2. book_element = dom.getElementsByTagName("book")[0]
  3. child_nodes = book_element.childNodes
  4. # 遍历子节点
  5. for i in range(child_nodes.length):
  6.     node = child_nodes.item(i)
  7.     if node.nodeType == node.ELEMENT_NODE:
  8.         print(f"{node.tagName}: {node.firstChild.data}")
复制代码
  1. // C#
  2. XmlElement bookElement = (XmlElement)xmlDoc.GetElementsByTagName("book")[0];
  3. XmlNodeList childNodes = bookElement.ChildNodes;
  4. // 遍历子节点
  5. foreach (XmlNode node in childNodes)
  6. {
  7.     if (node.NodeType == XmlNodeType.Element)
  8.     {
  9.         Console.WriteLine(node.Name + ": " + node.InnerText);
  10.     }
  11. }
复制代码
  1. // JavaScript
  2. let bookElement = xmlDoc.getElementsByTagName("book")[0];
  3. let firstChild = bookElement.firstChild;
  4. let lastChild = bookElement.lastChild;
  5. // 注意:firstChild和lastChild可能包括文本节点、注释节点等
  6. // 如果只想获取元素节点,可以使用firstElementChild和lastElementChild(如果支持)
  7. let firstElementChild = bookElement.firstElementChild || null;
  8. let lastElementChild = bookElement.lastElementChild || null;
复制代码
  1. // Java
  2. Element bookElement = (Element) document.getElementsByTagName("book").item(0);
  3. Node firstChild = bookElement.getFirstChild();
  4. Node lastChild = bookElement.getLastChild();
  5. // 获取第一个元素子节点
  6. Node firstElementChild = null;
  7. NodeList children = bookElement.getChildNodes();
  8. for (int i = 0; i < children.getLength(); i++) {
  9.   if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
  10.     firstElementChild = children.item(i);
  11.     break;
  12.   }
  13. }
复制代码
  1. # Python
  2. book_element = dom.getElementsByTagName("book")[0]
  3. first_child = book_element.firstChild
  4. last_child = book_element.lastChild
  5. # 获取第一个元素子节点
  6. first_element_child = None
  7. for child in book_element.childNodes:
  8.     if child.nodeType == child.ELEMENT_NODE:
  9.         first_element_child = child
  10.         break
复制代码
  1. // C#
  2. XmlElement bookElement = (XmlElement)xmlDoc.GetElementsByTagName("book")[0];
  3. XmlNode firstChild = bookElement.FirstChild;
  4. XmlNode lastChild = bookElement.LastChild;
  5. // 获取第一个元素子节点
  6. XmlNode firstElementChild = null;
  7. foreach (XmlNode node in bookElement.ChildNodes)
  8. {
  9.     if (node.NodeType == XmlNodeType.Element)
  10.     {
  11.         firstElementChild = node;
  12.         break;
  13.     }
  14. }
复制代码

兄弟节点访问
  1. // JavaScript
  2. let titleElement = xmlDoc.getElementsByTagName("title")[0];
  3. let previousSibling = titleElement.previousSibling;
  4. let nextSibling = titleElement.nextSibling;
  5. // 注意:previousSibling和nextSibling可能包括文本节点、注释节点等
  6. // 如果只想获取元素节点,可以使用previousElementSibling和nextElementSibling(如果支持)
  7. let previousElementSibling = titleElement.previousElementSibling || null;
  8. let nextElementSibling = titleElement.nextElementSibling || null;
复制代码
  1. // Java
  2. Element titleElement = (Element) document.getElementsByTagName("title").item(0);
  3. Node previousSibling = titleElement.getPreviousSibling();
  4. Node nextSibling = titleElement.getNextSibling();
  5. // 获取前一个元素兄弟节点
  6. Node previousElementSibling = null;
  7. Node node = titleElement.getPreviousSibling();
  8. while (node != null) {
  9.   if (node.getNodeType() == Node.ELEMENT_NODE) {
  10.     previousElementSibling = node;
  11.     break;
  12.   }
  13.   node = node.getPreviousSibling();
  14. }
复制代码
  1. # Python
  2. title_element = dom.getElementsByTagName("title")[0]
  3. previous_sibling = title_element.previousSibling
  4. next_sibling = title_element.nextSibling
  5. # 获取前一个元素兄弟节点
  6. previous_element_sibling = None
  7. node = title_element.previousSibling
  8. while node:
  9.     if node.nodeType == node.ELEMENT_NODE:
  10.         previous_element_sibling = node
  11.         break
  12.     node = node.previousSibling
复制代码
  1. // C#
  2. XmlElement titleElement = (XmlElement)xmlDoc.GetElementsByTagName("title")[0];
  3. XmlNode previousSibling = titleElement.PreviousSibling;
  4. XmlNode nextSibling = titleElement.NextSibling;
  5. // 获取前一个元素兄弟节点
  6. XmlNode previousElementSibling = null;
  7. XmlNode node = titleElement.PreviousSibling;
  8. while (node != null)
  9. {
  10.     if (node.NodeType == XmlNodeType.Element)
  11.     {
  12.         previousElementSibling = node;
  13.         break;
  14.     }
  15.     node = node.PreviousSibling;
  16. }
复制代码

节点查找

getElementsByTagName方法返回一个包含所有指定标签名的元素列表。
  1. // JavaScript
  2. let titles = xmlDoc.getElementsByTagName("title");
  3. for (let i = 0; i < titles.length; i++) {
  4.   console.log(titles[i].textContent);
  5. }
复制代码
  1. // Java
  2. NodeList titles = document.getElementsByTagName("title");
  3. for (int i = 0; i < titles.getLength(); i++) {
  4.   Element title = (Element) titles.item(i);
  5.   System.out.println(title.getTextContent());
  6. }
复制代码
  1. # Python
  2. titles = dom.getElementsByTagName("title")
  3. for i in range(titles.length):
  4.     title = titles.item(i)
  5.     print(title.firstChild.data)
复制代码
  1. // C#
  2. XmlNodeList titles = xmlDoc.GetElementsByTagName("title");
  3. foreach (XmlNode title in titles)
  4. {
  5.     Console.WriteLine(title.InnerText);
  6. }
复制代码

getElementById方法返回具有指定ID的元素。注意:要使此方法正常工作,XML文档必须有一个DTD或Schema定义了ID属性。
  1. // JavaScript
  2. // 假设XML文档中有一个元素有id="b001"
  3. let book = xmlDoc.getElementById("b001");
  4. if (book) {
  5.   console.log(book.getAttribute("category"));
  6. }
复制代码
  1. // Java
  2. // 假设XML文档中有一个元素有id="b001"
  3. Element book = document.getElementById("b001");
  4. if (book != null) {
  5.   System.out.println(book.getAttribute("category"));
  6. }
复制代码
  1. # Python
  2. # 假设XML文档中有一个元素有id="b001"
  3. book = dom.getElementById("b001")
  4. if book:
  5.     print(book.getAttribute("category"))
复制代码
  1. // C#
  2. // 假设XML文档中有一个元素有id="b001"
  3. XmlElement book = xmlDoc.GetElementById("b001");
  4. if (book != null)
  5. {
  6.     Console.WriteLine(book.GetAttribute("category"));
  7. }
复制代码

注意:getElementsByClassName方法在XML DOM中可能不被所有实现支持,它更常用于HTML DOM。
  1. // JavaScript
  2. // 假设XML文档中有一些元素有class="fiction"
  3. let fictionBooks = xmlDoc.getElementsByClassName("fiction");
  4. for (let i = 0; i < fictionBooks.length; i++) {
  5.   console.log(fictionBooks[i].textContent);
  6. }
复制代码

这些方法允许使用CSS选择器语法来查找元素,但请注意它们在XML DOM中的支持可能有限。
  1. // JavaScript
  2. // 查找所有category属性为"fiction"的book元素
  3. let fictionBooks = xmlDoc.querySelectorAll('book[category="fiction"]');
  4. for (let i = 0; i < fictionBooks.length; i++) {
  5.   console.log(fictionBooks[i].textContent);
  6. }
复制代码

高级属性获取技术

XPath查询

XPath是一种在XML文档中查找信息的语言,它提供了强大的查询能力,远超基本的DOM方法。

XPath使用路径表达式来选取XML文档中的节点或节点集。以下是一些基本的XPath表达式:

• /bookstore/book:选取根元素bookstore下的所有book元素
• //book:选取所有book元素,无论它们在文档中的位置
• //@lang:选取所有名为lang的属性
• /bookstore/book[1]:选取属于bookstore子元素的第一个book元素
• /bookstore/book[last()]:选取属于bookstore子元素的最后一个book元素
• /bookstore/book[price>35.00]:选取bookstore元素的所有book元素,且其中的price元素的值须大于35.00
• //title[@lang]:选取所有拥有名为lang的属性的title元素
• //title[@lang='en']:选取所有title元素,且这些元素拥有值为en的lang属性

在JavaScript中,可以使用evaluate方法来执行XPath查询:
  1. // 创建XPath评估器
  2. let xpathResult = xmlDoc.evaluate('//book[@category="fiction"]', xmlDoc, null, XPathResult.ANY_TYPE, null);
  3. let nodes = [];
  4. let node = xpathResult.iterateNext();
  5. while (node) {
  6.   nodes.push(node);
  7.   node = xpathResult.iterateNext();
  8. }
  9. // 输出结果
  10. nodes.forEach(function(node) {
  11.   console.log(node.getElementsByTagName("title")[0].textContent);
  12. });
复制代码

在Java中,可以使用XPath API:
  1. import javax.xml.xpath.*;
  2. // 创建XPath工厂
  3. XPathFactory xpathFactory = XPathFactory.newInstance();
  4. XPath xpath = xpathFactory.newXPath();
  5. try {
  6.   // 编译XPath表达式
  7.   XPathExpression expr = xpath.compile("//book[@category='fiction']");
  8.   
  9.   // 执行查询
  10.   NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
  11.   
  12.   // 输出结果
  13.   for (int i = 0; i < nodes.getLength(); i++) {
  14.     Element book = (Element) nodes.item(i);
  15.     Element title = (Element) book.getElementsByTagName("title").item(0);
  16.     System.out.println(title.getTextContent());
  17.   }
  18. } catch (XPathExpressionException e) {
  19.   e.printStackTrace();
  20. }
复制代码

在Python中,可以使用xpath方法(需要lxml库)或findall方法:
  1. # 使用lxml
  2. from lxml import etree
  3. # 解析XML文档
  4. tree = etree.parse("books.xml")
  5. root = tree.getroot()
  6. # 执行XPath查询
  7. books = root.xpath("//book[@category='fiction']")
  8. # 输出结果
  9. for book in books:
  10.     title = book.find("title")
  11.     print(title.text)
复制代码

在C#中,可以使用SelectNodes或SelectSingleNode方法:
  1. using System.Xml.XPath;
  2. // 执行XPath查询
  3. XmlNodeList nodes = xmlDoc.SelectNodes("//book[@category='fiction']");
  4. // 输出结果
  5. foreach (XmlNode node in nodes)
  6. {
  7.     XmlNode titleNode = node.SelectSingleNode("title");
  8.     Console.WriteLine(titleNode.InnerText);
  9. }
复制代码

XPath的强大之处在于它能够执行复杂的查询。以下是一些更复杂的XPath示例:
  1. // JavaScript示例
  2. // 查找价格大于20的书籍
  3. let expensiveBooks = xmlDoc.evaluate('//book[price>20]', xmlDoc, null, XPathResult.ANY_TYPE, null);
  4. // 查找作者为"J.K. Rowling"的书籍
  5. let rowlingBooks = xmlDoc.evaluate('//book[author="J.K. Rowling"]', xmlDoc, null, XPathResult.ANY_TYPE, null);
  6. // 查找标题包含"Potter"的书籍
  7. let potterBooks = xmlDoc.evaluate('//book[contains(title, "Potter")]', xmlDoc, null, XPathResult.ANY_TYPE, null);
  8. // 查找lang属性为"en"且category属性为"fiction"的书籍
  9. let specificBooks = xmlDoc.evaluate('//book[@category="fiction" and title/@lang="en"]', xmlDoc, null, XPathResult.ANY_TYPE, null);
  10. // 使用XPath函数
  11. // 查找价格最高的书籍
  12. let mostExpensiveBook = xmlDoc.evaluate('//book[price = max(//book/price)]', xmlDoc, null, XPathResult.ANY_TYPE, null);
复制代码

命名空间处理

当XML文档使用命名空间时,属性获取会变得稍微复杂。以下是如何处理带有命名空间的XML文档:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <bookstore xmlns:bs="http://www.example.com/bookstore"
  3.            xmlns:b="http://www.example.com/book">
  4.   <b:book bs:category="fiction">
  5.     <b:title b:lang="en">Harry Potter</b:title>
  6.     <b:author>J.K. Rowling</b:author>
  7.     <b:year>2005</b:year>
  8.     <b:price>29.99</b:price>
  9.   </b:book>
  10.   <b:book bs:category="children">
  11.     <b:title b:lang="en">The Wonderful Wizard of Oz</b:title>
  12.     <b:author>L. Frank Baum</b:author>
  13.     <b:year>1900</b:year>
  14.     <b:price>15.99</b:price>
  15.   </b:book>
  16. </bookstore>
复制代码
  1. // 创建命名空间解析器
  2. function nsResolver(prefix) {
  3.   var ns = {
  4.     'bs': 'http://www.example.com/bookstore',
  5.     'b': 'http://www.example.com/book'
  6.   };
  7.   return ns[prefix] || null;
  8. }
  9. // 使用命名空间执行XPath查询
  10. let xpathResult = xmlDoc.evaluate('//b:book[@bs:category="fiction"]', xmlDoc, nsResolver, XPathResult.ANY_TYPE, null);
  11. let nodes = [];
  12. let node = xpathResult.iterateNext();
  13. while (node) {
  14.   nodes.push(node);
  15.   node = xpathResult.iterateNext();
  16. }
  17. // 输出结果
  18. nodes.forEach(function(node) {
  19.   console.log(node.getElementsByTagNameNS("http://www.example.com/book", "title")[0].textContent);
  20. });
复制代码
  1. import javax.xml.namespace.NamespaceContext;
  2. import java.util.Iterator;
  3. // 创建命名空间上下文
  4. NamespaceContext nsContext = new NamespaceContext() {
  5.   @Override
  6.   public String getNamespaceURI(String prefix) {
  7.     if (prefix.equals("bs")) {
  8.       return "http://www.example.com/bookstore";
  9.     } else if (prefix.equals("b")) {
  10.       return "http://www.example.com/book";
  11.     }
  12.     return null;
  13.   }
  14.   @Override
  15.   public String getPrefix(String namespaceURI) {
  16.     return null;
  17.   }
  18.   @Override
  19.   public Iterator<String> getPrefixes(String namespaceURI) {
  20.     return null;
  21.   }
  22. };
  23. // 创建XPath工厂
  24. XPathFactory xpathFactory = XPathFactory.newInstance();
  25. XPath xpath = xpathFactory.newXPath();
  26. xpath.setNamespaceContext(nsContext);
  27. try {
  28.   // 编译XPath表达式
  29.   XPathExpression expr = xpath.compile("//b:book[@bs:category='fiction']");
  30.   
  31.   // 执行查询
  32.   NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
  33.   
  34.   // 输出结果
  35.   for (int i = 0; i < nodes.getLength(); i++) {
  36.     Element book = (Element) nodes.item(i);
  37.     NodeList titles = book.getElementsByTagNameNS("http://www.example.com/book", "title");
  38.     Element title = (Element) titles.item(0);
  39.     System.out.println(title.getTextContent());
  40.   }
  41. } catch (XPathExpressionException e) {
  42.   e.printStackTrace();
  43. }
复制代码
  1. # 使用lxml处理命名空间
  2. from lxml import etree
  3. # 定义命名空间
  4. namespaces = {
  5.     'bs': 'http://www.example.com/bookstore',
  6.     'b': 'http://www.example.com/book'
  7. }
  8. # 解析XML文档
  9. tree = etree.parse("books_ns.xml")
  10. root = tree.getroot()
  11. # 使用命名空间执行XPath查询
  12. books = root.xpath('//b:book[@bs:category="fiction"]', namespaces=namespaces)
  13. # 输出结果
  14. for book in books:
  15.     title = book.find('b:title', namespaces=namespaces)
  16.     print(title.text)
复制代码
  1. // 创建XmlNamespaceManager
  2. XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
  3. nsManager.AddNamespace("bs", "http://www.example.com/bookstore");
  4. nsManager.AddNamespace("b", "http://www.example.com/book");
  5. // 使用命名空间执行XPath查询
  6. XmlNodeList nodes = xmlDoc.SelectNodes("//b:book[@bs:category='fiction']", nsManager);
  7. // 输出结果
  8. foreach (XmlNode node in nodes)
  9. {
  10.     XmlNode titleNode = node.SelectSingleNode("b:title", nsManager);
  11.     Console.WriteLine(titleNode.InnerText);
  12. }
复制代码

属性值转换和验证

在实际应用中,我们经常需要将属性值转换为特定的数据类型,并验证其有效性。
  1. // 获取价格属性并转换为数字
  2. let priceElement = xmlDoc.getElementsByTagName("price")[0];
  3. let priceText = priceElement.textContent;
  4. let price = parseFloat(priceText);
  5. if (!isNaN(price)) {
  6.   console.log("Price is: " + price);
  7. } else {
  8.   console.log("Invalid price format");
  9. }
  10. // 获取年份属性并转换为整数
  11. let yearElement = xmlDoc.getElementsByTagName("year")[0];
  12. let yearText = yearElement.textContent;
  13. let year = parseInt(yearText, 10);
  14. if (!isNaN(year)) {
  15.   console.log("Year is: " + year);
  16. } else {
  17.   console.log("Invalid year format");
  18. }
复制代码
  1. // 获取价格元素并转换为double
  2. Element priceElement = (Element) document.getElementsByTagName("price").item(0);
  3. String priceText = priceElement.getTextContent();
  4. double price;
  5. try {
  6.   price = Double.parseDouble(priceText);
  7.   System.out.println("Price is: " + price);
  8. } catch (NumberFormatException e) {
  9.   System.out.println("Invalid price format");
  10. }
  11. // 获取年份元素并转换为整数
  12. Element yearElement = (Element) document.getElementsByTagName("year").item(0);
  13. String yearText = yearElement.getTextContent();
  14. int year;
  15. try {
  16.   year = Integer.parseInt(yearText);
  17.   System.out.println("Year is: " + year);
  18. } catch (NumberFormatException e) {
  19.   System.out.println("Invalid year format");
  20. }
复制代码
  1. # 获取价格元素并转换为浮点数
  2. price_element = dom.getElementsByTagName("price")[0]
  3. price_text = price_element.firstChild.data
  4. try:
  5.     price = float(price_text)
  6.     print(f"Price is: {price}")
  7. except ValueError:
  8.     print("Invalid price format")
  9. # 获取年份元素并转换为整数
  10. year_element = dom.getElementsByTagName("year")[0]
  11. year_text = year_element.firstChild.data
  12. try:
  13.     year = int(year_text)
  14.     print(f"Year is: {year}")
  15. except ValueError:
  16.     print("Invalid year format")
复制代码
  1. // 获取价格元素并转换为double
  2. XmlNode priceNode = xmlDoc.GetElementsByTagName("price")[0];
  3. string priceText = priceNode.InnerText;
  4. double price;
  5. if (double.TryParse(priceText, out price))
  6. {
  7.     Console.WriteLine("Price is: " + price);
  8. }
  9. else
  10. {
  11.     Console.WriteLine("Invalid price format");
  12. }
  13. // 获取年份元素并转换为整数
  14. XmlNode yearNode = xmlDoc.GetElementsByTagName("year")[0];
  15. string yearText = yearNode.InnerText;
  16. int year;
  17. if (int.TryParse(yearText, out year))
  18. {
  19.     Console.WriteLine("Year is: " + year);
  20. }
  21. else
  22. {
  23.     Console.WriteLine("Invalid year format");
  24. }
复制代码
  1. // 验证价格是否为正数
  2. function validatePrice(price) {
  3.   return !isNaN(price) && price > 0;
  4. }
  5. // 验证年份是否在合理范围内
  6. function validateYear(year) {
  7.   const currentYear = new Date().getFullYear();
  8.   return !isNaN(year) && year >= 1800 && year <= currentYear + 1;
  9. }
  10. // 使用验证函数
  11. let priceElement = xmlDoc.getElementsByTagName("price")[0];
  12. let price = parseFloat(priceElement.textContent);
  13. if (validatePrice(price)) {
  14.   console.log("Valid price: " + price);
  15. } else {
  16.   console.log("Invalid price: " + price);
  17. }
  18. let yearElement = xmlDoc.getElementsByTagName("year")[0];
  19. let year = parseInt(yearElement.textContent, 10);
  20. if (validateYear(year)) {
  21.   console.log("Valid year: " + year);
  22. } else {
  23.   console.log("Invalid year: " + year);
  24. }
复制代码
  1. // 验证价格是否为正数
  2. public static boolean validatePrice(double price) {
  3.   return !Double.isNaN(price) && price > 0;
  4. }
  5. // 验证年份是否在合理范围内
  6. public static boolean validateYear(int year) {
  7.   int currentYear = java.time.Year.now().getValue();
  8.   return year >= 1800 && year <= currentYear + 1;
  9. }
  10. // 使用验证方法
  11. Element priceElement = (Element) document.getElementsByTagName("price").item(0);
  12. double price = Double.parseDouble(priceElement.getTextContent());
  13. if (validatePrice(price)) {
  14.   System.out.println("Valid price: " + price);
  15. } else {
  16.   System.out.println("Invalid price: " + price);
  17. }
  18. Element yearElement = (Element) document.getElementsByTagName("year").item(0);
  19. int year = Integer.parseInt(yearElement.getTextContent());
  20. if (validateYear(year)) {
  21.   System.out.println("Valid year: " + year);
  22. } else {
  23.   System.out.println("Invalid year: " + year);
  24. }
复制代码
  1. import datetime
  2. # 验证价格是否为正数
  3. def validate_price(price):
  4.     return price > 0
  5. # 验证年份是否在合理范围内
  6. def validate_year(year):
  7.     current_year = datetime.datetime.now().year
  8.     return 1800 <= year <= current_year + 1
  9. # 使用验证函数
  10. price_element = dom.getElementsByTagName("price")[0]
  11. price = float(price_element.firstChild.data)
  12. if validate_price(price):
  13.     print(f"Valid price: {price}")
  14. else:
  15.     print(f"Invalid price: {price}")
  16. year_element = dom.getElementsByTagName("year")[0]
  17. year = int(year_element.firstChild.data)
  18. if validate_year(year):
  19.     print(f"Valid year: {year}")
  20. else:
  21.     print(f"Invalid year: {year}")
复制代码
  1. // 验证价格是否为正数
  2. public static bool ValidatePrice(double price)
  3. {
  4.   return !double.IsNaN(price) && price > 0;
  5. }
  6. // 验证年份是否在合理范围内
  7. public static bool ValidateYear(int year)
  8. {
  9.   int currentYear = DateTime.Now.Year;
  10.   return year >= 1800 && year <= currentYear + 1;
  11. }
  12. // 使用验证方法
  13. XmlNode priceNode = xmlDoc.GetElementsByTagName("price")[0];
  14. double price = double.Parse(priceNode.InnerText);
  15. if (ValidatePrice(price))
  16. {
  17.   Console.WriteLine("Valid price: " + price);
  18. }
  19. else
  20. {
  21.   Console.WriteLine("Invalid price: " + price);
  22. }
  23. XmlNode yearNode = xmlDoc.GetElementsByTagName("year")[0];
  24. int year = int.Parse(yearNode.InnerText);
  25. if (ValidateYear(year))
  26. {
  27.   Console.WriteLine("Valid year: " + year);
  28. }
  29. else
  30. {
  31.   Console.WriteLine("Invalid year: " + year);
  32. }
复制代码

实际应用案例

案例1:配置文件解析

假设我们有一个应用程序配置文件,需要读取并解析其中的设置:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <config>
  3.   <database>
  4.     <host type="string" required="true">localhost</host>
  5.     <port type="integer" required="true" min="1" max="65535">3306</port>
  6.     <username type="string" required="true">admin</username>
  7.     <password type="string" required="true" encrypted="true">s3cr3t</password>
  8.     <connectionTimeout type="integer" required="false" default="30">30</connectionTimeout>
  9.   </database>
  10.   <logging>
  11.     <level type="string" required="true" values="debug,info,warn,error">info</level>
  12.     <file type="string" required="false">app.log</file>
  13.     <maxSize type="integer" required="false" default="10485760">10485760</maxSize>
  14.   </logging>
  15. </config>
复制代码

以下是解析这个配置文件的代码示例:
  1. // 解析配置文件
  2. function parseConfig(xmlString) {
  3.   let parser = new DOMParser();
  4.   let xmlDoc = parser.parseFromString(xmlString, "text/xml");
  5.   let config = {};
  6.   
  7.   // 解析数据库配置
  8.   let databaseConfig = {};
  9.   let databaseNode = xmlDoc.getElementsByTagName("database")[0];
  10.   
  11.   let hostNode = databaseNode.getElementsByTagName("host")[0];
  12.   databaseConfig.host = {
  13.     value: hostNode.textContent,
  14.     type: hostNode.getAttribute("type"),
  15.     required: hostNode.getAttribute("required") === "true"
  16.   };
  17.   
  18.   let portNode = databaseNode.getElementsByTagName("port")[0];
  19.   databaseConfig.port = {
  20.     value: parseInt(portNode.textContent, 10),
  21.     type: portNode.getAttribute("type"),
  22.     required: portNode.getAttribute("required") === "true",
  23.     min: parseInt(portNode.getAttribute("min"), 10),
  24.     max: parseInt(portNode.getAttribute("max"), 10)
  25.   };
  26.   
  27.   let usernameNode = databaseNode.getElementsByTagName("username")[0];
  28.   databaseConfig.username = {
  29.     value: usernameNode.textContent,
  30.     type: usernameNode.getAttribute("type"),
  31.     required: usernameNode.getAttribute("required") === "true"
  32.   };
  33.   
  34.   let passwordNode = databaseNode.getElementsByTagName("password")[0];
  35.   databaseConfig.password = {
  36.     value: passwordNode.textContent,
  37.     type: passwordNode.getAttribute("type"),
  38.     required: passwordNode.getAttribute("required") === "true",
  39.     encrypted: passwordNode.getAttribute("encrypted") === "true"
  40.   };
  41.   
  42.   let connectionTimeoutNode = databaseNode.getElementsByTagName("connectionTimeout")[0];
  43.   databaseConfig.connectionTimeout = {
  44.     value: parseInt(connectionTimeoutNode.textContent, 10),
  45.     type: connectionTimeoutNode.getAttribute("type"),
  46.     required: connectionTimeoutNode.getAttribute("required") === "true",
  47.     default: parseInt(connectionTimeoutNode.getAttribute("default"), 10)
  48.   };
  49.   
  50.   config.database = databaseConfig;
  51.   
  52.   // 解析日志配置
  53.   let loggingConfig = {};
  54.   let loggingNode = xmlDoc.getElementsByTagName("logging")[0];
  55.   
  56.   let levelNode = loggingNode.getElementsByTagName("level")[0];
  57.   loggingConfig.level = {
  58.     value: levelNode.textContent,
  59.     type: levelNode.getAttribute("type"),
  60.     required: levelNode.getAttribute("required") === "true",
  61.     values: levelNode.getAttribute("values").split(",")
  62.   };
  63.   
  64.   let fileNode = loggingNode.getElementsByTagName("file")[0];
  65.   loggingConfig.file = {
  66.     value: fileNode.textContent,
  67.     type: fileNode.getAttribute("type"),
  68.     required: fileNode.getAttribute("required") === "true"
  69.   };
  70.   
  71.   let maxSizeNode = loggingNode.getElementsByTagName("maxSize")[0];
  72.   loggingConfig.maxSize = {
  73.     value: parseInt(maxSizeNode.textContent, 10),
  74.     type: maxSizeNode.getAttribute("type"),
  75.     required: maxSizeNode.getAttribute("required") === "true",
  76.     default: parseInt(maxSizeNode.getAttribute("default"), 10)
  77.   };
  78.   
  79.   config.logging = loggingConfig;
  80.   
  81.   return config;
  82. }
  83. // 使用示例
  84. let configXml = `<?xml version="1.0" encoding="UTF-8"?>
  85. <config>
  86.   <database>
  87.     <host type="string" required="true">localhost</host>
  88.     <port type="integer" required="true" min="1" max="65535">3306</port>
  89.     <username type="string" required="true">admin</username>
  90.     <password type="string" required="true" encrypted="true">s3cr3t</password>
  91.     <connectionTimeout type="integer" required="false" default="30">30</connectionTimeout>
  92.   </database>
  93.   <logging>
  94.     <level type="string" required="true" values="debug,info,warn,error">info</level>
  95.     <file type="string" required="false">app.log</file>
  96.     <maxSize type="integer" required="false" default="10485760">10485760</maxSize>
  97.   </logging>
  98. </config>`;
  99. let config = parseConfig(configXml);
  100. console.log(JSON.stringify(config, null, 2));
复制代码
  1. import org.w3c.dom.*;
  2. import javax.xml.parsers.*;
  3. import java.io.*;
  4. public class ConfigParser {
  5.   public static Config parseConfig(String xmlString) throws Exception {
  6.     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  7.     DocumentBuilder builder = factory.newDocumentBuilder();
  8.     Document document = builder.parse(new ByteArrayInputStream(xmlString.getBytes()));
  9.    
  10.     Config config = new Config();
  11.    
  12.     // 解析数据库配置
  13.     DatabaseConfig databaseConfig = new DatabaseConfig();
  14.     Element databaseNode = (Element) document.getElementsByTagName("database").item(0);
  15.    
  16.     Element hostNode = (Element) databaseNode.getElementsByTagName("host").item(0);
  17.     databaseConfig.setHost(new ConfigValue(
  18.       hostNode.getTextContent(),
  19.       hostNode.getAttribute("type"),
  20.       Boolean.parseBoolean(hostNode.getAttribute("required"))
  21.     ));
  22.    
  23.     Element portNode = (Element) databaseNode.getElementsByTagName("port").item(0);
  24.     databaseConfig.setPort(new ConfigValue(
  25.       Integer.parseInt(portNode.getTextContent()),
  26.       portNode.getAttribute("type"),
  27.       Boolean.parseBoolean(portNode.getAttribute("required")),
  28.       Integer.parseInt(portNode.getAttribute("min")),
  29.       Integer.parseInt(portNode.getAttribute("max"))
  30.     ));
  31.    
  32.     Element usernameNode = (Element) databaseNode.getElementsByTagName("username").item(0);
  33.     databaseConfig.setUsername(new ConfigValue(
  34.       usernameNode.getTextContent(),
  35.       usernameNode.getAttribute("type"),
  36.       Boolean.parseBoolean(usernameNode.getAttribute("required"))
  37.     ));
  38.    
  39.     Element passwordNode = (Element) databaseNode.getElementsByTagName("password").item(0);
  40.     databaseConfig.setPassword(new ConfigValue(
  41.       passwordNode.getTextContent(),
  42.       passwordNode.getAttribute("type"),
  43.       Boolean.parseBoolean(passwordNode.getAttribute("required")),
  44.       Boolean.parseBoolean(passwordNode.getAttribute("encrypted"))
  45.     ));
  46.    
  47.     Element connectionTimeoutNode = (Element) databaseNode.getElementsByTagName("connectionTimeout").item(0);
  48.     databaseConfig.setConnectionTimeout(new ConfigValue(
  49.       Integer.parseInt(connectionTimeoutNode.getTextContent()),
  50.       connectionTimeoutNode.getAttribute("type"),
  51.       Boolean.parseBoolean(connectionTimeoutNode.getAttribute("required")),
  52.       Integer.parseInt(connectionTimeoutNode.getAttribute("default"))
  53.     ));
  54.    
  55.     config.setDatabase(databaseConfig);
  56.    
  57.     // 解析日志配置
  58.     LoggingConfig loggingConfig = new LoggingConfig();
  59.     Element loggingNode = (Element) document.getElementsByTagName("logging").item(0);
  60.    
  61.     Element levelNode = (Element) loggingNode.getElementsByTagName("level").item(0);
  62.     loggingConfig.setLevel(new ConfigValue(
  63.       levelNode.getTextContent(),
  64.       levelNode.getAttribute("type"),
  65.       Boolean.parseBoolean(levelNode.getAttribute("required")),
  66.       levelNode.getAttribute("values").split(",")
  67.     ));
  68.    
  69.     Element fileNode = (Element) loggingNode.getElementsByTagName("file").item(0);
  70.     loggingConfig.setFile(new ConfigValue(
  71.       fileNode.getTextContent(),
  72.       fileNode.getAttribute("type"),
  73.       Boolean.parseBoolean(fileNode.getAttribute("required"))
  74.     ));
  75.    
  76.     Element maxSizeNode = (Element) loggingNode.getElementsByTagName("maxSize").item(0);
  77.     loggingConfig.setMaxSize(new ConfigValue(
  78.       Integer.parseInt(maxSizeNode.getTextContent()),
  79.       maxSizeNode.getAttribute("type"),
  80.       Boolean.parseBoolean(maxSizeNode.getAttribute("required")),
  81.       Integer.parseInt(maxSizeNode.getAttribute("default"))
  82.     ));
  83.    
  84.     config.setLogging(loggingConfig);
  85.    
  86.     return config;
  87.   }
  88.   
  89.   // 配置类
  90.   public static class Config {
  91.     private DatabaseConfig database;
  92.     private LoggingConfig logging;
  93.    
  94.     // getters and setters
  95.   }
  96.   
  97.   public static class DatabaseConfig {
  98.     private ConfigValue host;
  99.     private ConfigValue port;
  100.     private ConfigValue username;
  101.     private ConfigValue password;
  102.     private ConfigValue connectionTimeout;
  103.    
  104.     // getters and setters
  105.   }
  106.   
  107.   public static class LoggingConfig {
  108.     private ConfigValue level;
  109.     private ConfigValue file;
  110.     private ConfigValue maxSize;
  111.    
  112.     // getters and setters
  113.   }
  114.   
  115.   public static class ConfigValue {
  116.     private Object value;
  117.     private String type;
  118.     private boolean required;
  119.     private Object[] constraints;
  120.    
  121.     public ConfigValue(Object value, String type, boolean required, Object... constraints) {
  122.       this.value = value;
  123.       this.type = type;
  124.       this.required = required;
  125.       this.constraints = constraints;
  126.     }
  127.    
  128.     // getters
  129.   }
  130.   
  131.   public static void main(String[] args) {
  132.     try {
  133.       String configXml = "<?xml version="1.0" encoding="UTF-8"?>\n" +
  134.                          "<config>\n" +
  135.                          "  <database>\n" +
  136.                          "    <host type="string" required="true">localhost</host>\n" +
  137.                          "    <port type="integer" required="true" min="1" max="65535">3306</port>\n" +
  138.                          "    <username type="string" required="true">admin</username>\n" +
  139.                          "    <password type="string" required="true" encrypted="true">s3cr3t</password>\n" +
  140.                          "    <connectionTimeout type="integer" required="false" default="30">30</connectionTimeout>\n" +
  141.                          "  </database>\n" +
  142.                          "  <logging>\n" +
  143.                          "    <level type="string" required="true" values="debug,info,warn,error">info</level>\n" +
  144.                          "    <file type="string" required="false">app.log</file>\n" +
  145.                          "    <maxSize type="integer" required="false" default="10485760">10485760</maxSize>\n" +
  146.                          "  </logging>\n" +
  147.                          "</config>";
  148.       
  149.       Config config = parseConfig(configXml);
  150.       System.out.println(config.toString());
  151.     } catch (Exception e) {
  152.       e.printStackTrace();
  153.     }
  154.   }
  155. }
复制代码
  1. from xml.dom.minidom import parseString
  2. def parse_config(xml_string):
  3.     dom = parseString(xml_string)
  4.     config = {}
  5.    
  6.     # 解析数据库配置
  7.     database_config = {}
  8.     database_node = dom.getElementsByTagName("database")[0]
  9.    
  10.     host_node = database_node.getElementsByTagName("host")[0]
  11.     database_config['host'] = {
  12.         'value': host_node.firstChild.data,
  13.         'type': host_node.getAttribute("type"),
  14.         'required': host_node.getAttribute("required") == "true"
  15.     }
  16.    
  17.     port_node = database_node.getElementsByTagName("port")[0]
  18.     database_config['port'] = {
  19.         'value': int(port_node.firstChild.data),
  20.         'type': port_node.getAttribute("type"),
  21.         'required': port_node.getAttribute("required") == "true",
  22.         'min': int(port_node.getAttribute("min")),
  23.         'max': int(port_node.getAttribute("max"))
  24.     }
  25.    
  26.     username_node = database_node.getElementsByTagName("username")[0]
  27.     database_config['username'] = {
  28.         'value': username_node.firstChild.data,
  29.         'type': username_node.getAttribute("type"),
  30.         'required': username_node.getAttribute("required") == "true"
  31.     }
  32.    
  33.     password_node = database_node.getElementsByTagName("password")[0]
  34.     database_config['password'] = {
  35.         'value': password_node.firstChild.data,
  36.         'type': password_node.getAttribute("type"),
  37.         'required': password_node.getAttribute("required") == "true",
  38.         'encrypted': password_node.getAttribute("encrypted") == "true"
  39.     }
  40.    
  41.     connection_timeout_node = database_node.getElementsByTagName("connectionTimeout")[0]
  42.     database_config['connectionTimeout'] = {
  43.         'value': int(connection_timeout_node.firstChild.data),
  44.         'type': connection_timeout_node.getAttribute("type"),
  45.         'required': connection_timeout_node.getAttribute("required") == "true",
  46.         'default': int(connection_timeout_node.getAttribute("default"))
  47.     }
  48.    
  49.     config['database'] = database_config
  50.    
  51.     # 解析日志配置
  52.     logging_config = {}
  53.     logging_node = dom.getElementsByTagName("logging")[0]
  54.    
  55.     level_node = logging_node.getElementsByTagName("level")[0]
  56.     logging_config['level'] = {
  57.         'value': level_node.firstChild.data,
  58.         'type': level_node.getAttribute("type"),
  59.         'required': level_node.getAttribute("required") == "true",
  60.         'values': level_node.getAttribute("values").split(",")
  61.     }
  62.    
  63.     file_node = logging_node.getElementsByTagName("file")[0]
  64.     logging_config['file'] = {
  65.         'value': file_node.firstChild.data,
  66.         'type': file_node.getAttribute("type"),
  67.         'required': file_node.getAttribute("required") == "true"
  68.     }
  69.    
  70.     max_size_node = logging_node.getElementsByTagName("maxSize")[0]
  71.     logging_config['maxSize'] = {
  72.         'value': int(max_size_node.firstChild.data),
  73.         'type': max_size_node.getAttribute("type"),
  74.         'required': max_size_node.getAttribute("required") == "true",
  75.         'default': int(max_size_node.getAttribute("default"))
  76.     }
  77.    
  78.     config['logging'] = logging_config
  79.    
  80.     return config
  81. # 使用示例
  82. config_xml = """<?xml version="1.0" encoding="UTF-8"?>
  83. <config>
  84.   <database>
  85.     <host type="string" required="true">localhost</host>
  86.     <port type="integer" required="true" min="1" max="65535">3306</port>
  87.     <username type="string" required="true">admin</username>
  88.     <password type="string" required="true" encrypted="true">s3cr3t</password>
  89.     <connectionTimeout type="integer" required="false" default="30">30</connectionTimeout>
  90.   </database>
  91.   <logging>
  92.     <level type="string" required="true" values="debug,info,warn,error">info</level>
  93.     <file type="string" required="false">app.log</file>
  94.     <maxSize type="integer" required="false" default="10485760">10485760</maxSize>
  95.   </logging>
  96. </config>"""
  97. config = parse_config(config_xml)
  98. import json
  99. print(json.dumps(config, indent=2))
复制代码
  1. using System;
  2. using System.Xml;
  3. using System.Collections.Generic;
  4. public class ConfigParser
  5. {
  6.   public static Config ParseConfig(string xmlString)
  7.   {
  8.     XmlDocument xmlDoc = new XmlDocument();
  9.     xmlDoc.LoadXml(xmlString);
  10.    
  11.     Config config = new Config();
  12.    
  13.     // 解析数据库配置
  14.     DatabaseConfig databaseConfig = new DatabaseConfig();
  15.     XmlNode databaseNode = xmlDoc.SelectSingleNode("//database");
  16.    
  17.     XmlNode hostNode = databaseNode.SelectSingleNode("host");
  18.     databaseConfig.Host = new ConfigValue(
  19.       hostNode.InnerText,
  20.       hostNode.Attributes["type"].Value,
  21.       bool.Parse(hostNode.Attributes["required"].Value)
  22.     );
  23.    
  24.     XmlNode portNode = databaseNode.SelectSingleNode("port");
  25.     databaseConfig.Port = new ConfigValue(
  26.       int.Parse(portNode.InnerText),
  27.       portNode.Attributes["type"].Value,
  28.       bool.Parse(portNode.Attributes["required"].Value),
  29.       int.Parse(portNode.Attributes["min"].Value),
  30.       int.Parse(portNode.Attributes["max"].Value)
  31.     );
  32.    
  33.     XmlNode usernameNode = databaseNode.SelectSingleNode("username");
  34.     databaseConfig.Username = new ConfigValue(
  35.       usernameNode.InnerText,
  36.       usernameNode.Attributes["type"].Value,
  37.       bool.Parse(usernameNode.Attributes["required"].Value)
  38.     );
  39.    
  40.     XmlNode passwordNode = databaseNode.SelectSingleNode("password");
  41.     databaseConfig.Password = new ConfigValue(
  42.       passwordNode.InnerText,
  43.       passwordNode.Attributes["type"].Value,
  44.       bool.Parse(passwordNode.Attributes["required"].Value),
  45.       bool.Parse(passwordNode.Attributes["encrypted"].Value)
  46.     );
  47.    
  48.     XmlNode connectionTimeoutNode = databaseNode.SelectSingleNode("connectionTimeout");
  49.     databaseConfig.ConnectionTimeout = new ConfigValue(
  50.       int.Parse(connectionTimeoutNode.InnerText),
  51.       connectionTimeoutNode.Attributes["type"].Value,
  52.       bool.Parse(connectionTimeoutNode.Attributes["required"].Value),
  53.       int.Parse(connectionTimeoutNode.Attributes["default"].Value)
  54.     );
  55.    
  56.     config.Database = databaseConfig;
  57.    
  58.     // 解析日志配置
  59.     LoggingConfig loggingConfig = new LoggingConfig();
  60.     XmlNode loggingNode = xmlDoc.SelectSingleNode("//logging");
  61.    
  62.     XmlNode levelNode = loggingNode.SelectSingleNode("level");
  63.     loggingConfig.Level = new ConfigValue(
  64.       levelNode.InnerText,
  65.       levelNode.Attributes["type"].Value,
  66.       bool.Parse(levelNode.Attributes["required"].Value),
  67.       levelNode.Attributes["values"].Value.Split(',')
  68.     );
  69.    
  70.     XmlNode fileNode = loggingNode.SelectSingleNode("file");
  71.     loggingConfig.File = new ConfigValue(
  72.       fileNode.InnerText,
  73.       fileNode.Attributes["type"].Value,
  74.       bool.Parse(fileNode.Attributes["required"].Value)
  75.     );
  76.    
  77.     XmlNode maxSizeNode = loggingNode.SelectSingleNode("maxSize");
  78.     loggingConfig.MaxSize = new ConfigValue(
  79.       int.Parse(maxSizeNode.InnerText),
  80.       maxSizeNode.Attributes["type"].Value,
  81.       bool.Parse(maxSizeNode.Attributes["required"].Value),
  82.       int.Parse(maxSizeNode.Attributes["default"].Value)
  83.     );
  84.    
  85.     config.Logging = loggingConfig;
  86.    
  87.     return config;
  88.   }
  89.   
  90.   // 配置类
  91.   public class Config
  92.   {
  93.     public DatabaseConfig Database { get; set; }
  94.     public LoggingConfig Logging { get; set; }
  95.   }
  96.   
  97.   public class DatabaseConfig
  98.   {
  99.     public ConfigValue Host { get; set; }
  100.     public ConfigValue Port { get; set; }
  101.     public ConfigValue Username { get; set; }
  102.     public ConfigValue Password { get; set; }
  103.     public ConfigValue ConnectionTimeout { get; set; }
  104.   }
  105.   
  106.   public class LoggingConfig
  107.   {
  108.     public ConfigValue Level { get; set; }
  109.     public ConfigValue File { get; set; }
  110.     public ConfigValue MaxSize { get; set; }
  111.   }
  112.   
  113.   public class ConfigValue
  114.   {
  115.     public object Value { get; set; }
  116.     public string Type { get; set; }
  117.     public bool Required { get; set; }
  118.     public object[] Constraints { get; set; }
  119.    
  120.     public ConfigValue(object value, string type, bool required, params object[] constraints)
  121.     {
  122.       Value = value;
  123.       Type = type;
  124.       Required = required;
  125.       Constraints = constraints;
  126.     }
  127.   }
  128.   
  129.   public static void Main(string[] args)
  130.   {
  131.     string configXml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
  132. <config>
  133.   <database>
  134.     <host type=""string"" required=""true"">localhost</host>
  135.     <port type=""integer"" required=""true"" min=""1"" max=""65535"">3306</port>
  136.     <username type=""string"" required=""true"">admin</username>
  137.     <password type=""string"" required=""true"" encrypted=""true"">s3cr3t</password>
  138.     <connectionTimeout type=""integer"" required=""false"" default=""30"">30</connectionTimeout>
  139.   </database>
  140.   <logging>
  141.     <level type=""string"" required=""true"" values=""debug,info,warn,error"">info</level>
  142.     <file type=""string"" required=""false"">app.log</file>
  143.     <maxSize type=""integer"" required=""false"" default=""10485760"">10485760</maxSize>
  144.   </logging>
  145. </config>";
  146.    
  147.     Config config = ParseConfig(configXml);
  148.     Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(config, Newtonsoft.Json.Formatting.Indented));
  149.   }
  150. }
复制代码

案例2:XML数据转换

假设我们需要将一个XML格式的产品目录转换为另一种格式,例如从内部格式转换为外部交换格式:

原始XML格式:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <catalog>
  3.   <product id="p001" category="electronics">
  4.     <name>Smartphone</name>
  5.     <description>A high-end smartphone with advanced features</description>
  6.     <price currency="USD">699.99</price>
  7.     <stock>50</stock>
  8.     <specifications>
  9.       <spec name="display">6.1 inch OLED</spec>
  10.       <spec name="storage">128GB</spec>
  11.       <spec name="ram">6GB</spec>
  12.       <spec name="camera">12MP dual camera</spec>
  13.     </specifications>
  14.   </product>
  15.   <product id="p002" category="electronics">
  16.     <name>Laptop</name>
  17.     <description>Powerful laptop for professionals</description>
  18.     <price currency="USD">1299.99</price>
  19.     <stock>25</stock>
  20.     <specifications>
  21.       <spec name="display">15.6 inch Full HD</spec>
  22.       <spec name="storage">512GB SSD</spec>
  23.       <spec name="ram">16GB</spec>
  24.       <spec name="processor">Intel Core i7</spec>
  25.     </specifications>
  26.   </product>
  27. </catalog>
复制代码

目标XML格式:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <productList xmlns="http://www.example.com/products">
  3.   <product sku="p001" type="electronics">
  4.     <title>Smartphone</title>
  5.     <details>A high-end smartphone with advanced features</details>
  6.     <cost currency="USD">699.99</cost>
  7.     <inventory>50</inventory>
  8.     <features>
  9.       <feature key="display">6.1 inch OLED</feature>
  10.       <feature key="storage">128GB</feature>
  11.       <feature key="ram">6GB</feature>
  12.       <feature key="camera">12MP dual camera</feature>
  13.     </features>
  14.   </product>
  15.   <product sku="p002" type="electronics">
  16.     <title>Laptop</title>
  17.     <details>Powerful laptop for professionals</details>
  18.     <cost currency="USD">1299.99</cost>
  19.     <inventory>25</inventory>
  20.     <features>
  21.       <feature key="display">15.6 inch Full HD</feature>
  22.       <feature key="storage">512GB SSD</feature>
  23.       <feature key="ram">16GB</feature>
  24.       <feature key="processor">Intel Core i7</feature>
  25.     </features>
  26.   </product>
  27. </productList>
复制代码

以下是实现这种转换的代码示例:
  1. // 转换XML格式
  2. function transformProductCatalog(inputXmlString) {
  3.   // 解析输入XML
  4.   let parser = new DOMParser();
  5.   let inputDoc = parser.parseFromString(inputXmlString, "text/xml");
  6.   
  7.   // 创建输出XML文档
  8.   let outputDoc = document.implementation.createDocument("http://www.example.com/products", "productList", null);
  9.   let productList = outputDoc.documentElement;
  10.   
  11.   // 获取所有产品节点
  12.   let products = inputDoc.getElementsByTagName("product");
  13.   
  14.   // 遍历每个产品
  15.   for (let i = 0; i < products.length; i++) {
  16.     let inputProduct = products[i];
  17.    
  18.     // 创建产品节点
  19.     let outputProduct = outputDoc.createElementNS("http://www.example.com/products", "product");
  20.    
  21.     // 设置属性
  22.     outputProduct.setAttribute("sku", inputProduct.getAttribute("id"));
  23.     outputProduct.setAttribute("type", inputProduct.getAttribute("category"));
  24.    
  25.     // 添加子元素
  26.     let name = inputProduct.getElementsByTagName("name")[0];
  27.     let title = outputDoc.createElementNS("http://www.example.com/products", "title");
  28.     title.appendChild(outputDoc.createTextNode(name.textContent));
  29.     outputProduct.appendChild(title);
  30.    
  31.     let description = inputProduct.getElementsByTagName("description")[0];
  32.     let details = outputDoc.createElementNS("http://www.example.com/products", "details");
  33.     details.appendChild(outputDoc.createTextNode(description.textContent));
  34.     outputProduct.appendChild(details);
  35.    
  36.     let price = inputProduct.getElementsByTagName("price")[0];
  37.     let cost = outputDoc.createElementNS("http://www.example.com/products", "cost");
  38.     cost.setAttribute("currency", price.getAttribute("currency"));
  39.     cost.appendChild(outputDoc.createTextNode(price.textContent));
  40.     outputProduct.appendChild(cost);
  41.    
  42.     let stock = inputProduct.getElementsByTagName("stock")[0];
  43.     let inventory = outputDoc.createElementNS("http://www.example.com/products", "inventory");
  44.     inventory.appendChild(outputDoc.createTextNode(stock.textContent));
  45.     outputProduct.appendChild(inventory);
  46.    
  47.     // 处理规格/特性
  48.     let specifications = inputProduct.getElementsByTagName("specifications")[0];
  49.     let specs = specifications.getElementsByTagName("spec");
  50.     let features = outputDoc.createElementNS("http://www.example.com/products", "features");
  51.    
  52.     for (let j = 0; j < specs.length; j++) {
  53.       let spec = specs[j];
  54.       let feature = outputDoc.createElementNS("http://www.example.com/products", "feature");
  55.       feature.setAttribute("key", spec.getAttribute("name"));
  56.       feature.appendChild(outputDoc.createTextNode(spec.textContent));
  57.       features.appendChild(feature);
  58.     }
  59.    
  60.     outputProduct.appendChild(features);
  61.    
  62.     // 将产品添加到产品列表
  63.     productList.appendChild(outputProduct);
  64.   }
  65.   
  66.   // 序列化输出XML
  67.   let serializer = new XMLSerializer();
  68.   return serializer.serializeToString(outputDoc);
  69. }
  70. // 使用示例
  71. let inputXml = `<?xml version="1.0" encoding="UTF-8"?>
  72. <catalog>
  73.   <product id="p001" category="electronics">
  74.     <name>Smartphone</name>
  75.     <description>A high-end smartphone with advanced features</description>
  76.     <price currency="USD">699.99</price>
  77.     <stock>50</stock>
  78.     <specifications>
  79.       <spec name="display">6.1 inch OLED</spec>
  80.       <spec name="storage">128GB</spec>
  81.       <spec name="ram">6GB</spec>
  82.       <spec name="camera">12MP dual camera</spec>
  83.     </specifications>
  84.   </product>
  85.   <product id="p002" category="electronics">
  86.     <name>Laptop</name>
  87.     <description>Powerful laptop for professionals</description>
  88.     <price currency="USD">1299.99</price>
  89.     <stock>25</stock>
  90.     <specifications>
  91.       <spec name="display">15.6 inch Full HD</spec>
  92.       <spec name="storage">512GB SSD</spec>
  93.       <spec name="ram">16GB</spec>
  94.       <spec name="processor">Intel Core i7</spec>
  95.     </specifications>
  96.   </product>
  97. </catalog>`;
  98. let outputXml = transformProductCatalog(inputXml);
  99. console.log(outputXml);
复制代码
  1. import org.w3c.dom.*;
  2. import javax.xml.parsers.*;
  3. import javax.xml.transform.*;
  4. import javax.xml.transform.dom.DOMSource;
  5. import javax.xml.transform.stream.StreamResult;
  6. import java.io.*;
  7. public class ProductCatalogTransformer {
  8.   public static String transformProductCatalog(String inputXmlString) throws Exception {
  9.     // 解析输入XML
  10.     DocumentBuilderFactory inputFactory = DocumentBuilderFactory.newInstance();
  11.     DocumentBuilder inputBuilder = inputFactory.newDocumentBuilder();
  12.     Document inputDoc = inputBuilder.parse(new ByteArrayInputStream(inputXmlString.getBytes()));
  13.    
  14.     // 创建输出XML文档
  15.     DocumentBuilderFactory outputFactory = DocumentBuilderFactory.newInstance();
  16.     outputFactory.setNamespaceAware(true);
  17.     DocumentBuilder outputBuilder = outputFactory.newDocumentBuilder();
  18.     Document outputDoc = outputBuilder.newDocument();
  19.    
  20.     // 创建根元素
  21.     Element productList = outputDoc.createElementNS("http://www.example.com/products", "productList");
  22.     outputDoc.appendChild(productList);
  23.    
  24.     // 获取所有产品节点
  25.     NodeList products = inputDoc.getElementsByTagName("product");
  26.    
  27.     // 遍历每个产品
  28.     for (int i = 0; i < products.getLength(); i++) {
  29.       Element inputProduct = (Element) products.item(i);
  30.       
  31.       // 创建产品节点
  32.       Element outputProduct = outputDoc.createElementNS("http://www.example.com/products", "product");
  33.       
  34.       // 设置属性
  35.       outputProduct.setAttribute("sku", inputProduct.getAttribute("id"));
  36.       outputProduct.setAttribute("type", inputProduct.getAttribute("category"));
  37.       
  38.       // 添加子元素
  39.       Element name = (Element) inputProduct.getElementsByTagName("name").item(0);
  40.       Element title = outputDoc.createElementNS("http://www.example.com/products", "title");
  41.       title.appendChild(outputDoc.createTextNode(name.getTextContent()));
  42.       outputProduct.appendChild(title);
  43.       
  44.       Element description = (Element) inputProduct.getElementsByTagName("description").item(0);
  45.       Element details = outputDoc.createElementNS("http://www.example.com/products", "details");
  46.       details.appendChild(outputDoc.createTextNode(description.getTextContent()));
  47.       outputProduct.appendChild(details);
  48.       
  49.       Element price = (Element) inputProduct.getElementsByTagName("price").item(0);
  50.       Element cost = outputDoc.createElementNS("http://www.example.com/products", "cost");
  51.       cost.setAttribute("currency", price.getAttribute("currency"));
  52.       cost.appendChild(outputDoc.createTextNode(price.getTextContent()));
  53.       outputProduct.appendChild(cost);
  54.       
  55.       Element stock = (Element) inputProduct.getElementsByTagName("stock").item(0);
  56.       Element inventory = outputDoc.createElementNS("http://www.example.com/products", "inventory");
  57.       inventory.appendChild(outputDoc.createTextNode(stock.getTextContent()));
  58.       outputProduct.appendChild(inventory);
  59.       
  60.       // 处理规格/特性
  61.       Element specifications = (Element) inputProduct.getElementsByTagName("specifications").item(0);
  62.       NodeList specs = specifications.getElementsByTagName("spec");
  63.       Element features = outputDoc.createElementNS("http://www.example.com/products", "features");
  64.       
  65.       for (int j = 0; j < specs.getLength(); j++) {
  66.         Element spec = (Element) specs.item(j);
  67.         Element feature = outputDoc.createElementNS("http://www.example.com/products", "feature");
  68.         feature.setAttribute("key", spec.getAttribute("name"));
  69.         feature.appendChild(outputDoc.createTextNode(spec.getTextContent()));
  70.         features.appendChild(feature);
  71.       }
  72.       
  73.       outputProduct.appendChild(features);
  74.       
  75.       // 将产品添加到产品列表
  76.       productList.appendChild(outputProduct);
  77.     }
  78.    
  79.     // 序列化输出XML
  80.     TransformerFactory transformerFactory = TransformerFactory.newInstance();
  81.     Transformer transformer = transformerFactory.newTransformer();
  82.     transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  83.     transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
  84.    
  85.     StringWriter writer = new StringWriter();
  86.     transformer.transform(new DOMSource(outputDoc), new StreamResult(writer));
  87.    
  88.     return writer.toString();
  89.   }
  90.   
  91.   public static void main(String[] args) {
  92.     try {
  93.       String inputXml = "<?xml version="1.0" encoding="UTF-8"?>\n" +
  94.                         "<catalog>\n" +
  95.                         "  <product id="p001" category="electronics">\n" +
  96.                         "    <name>Smartphone</name>\n" +
  97.                         "    <description>A high-end smartphone with advanced features</description>\n" +
  98.                         "    <price currency="USD">699.99</price>\n" +
  99.                         "    <stock>50</stock>\n" +
  100.                         "    <specifications>\n" +
  101.                         "      <spec name="display">6.1 inch OLED</spec>\n" +
  102.                         "      <spec name="storage">128GB</spec>\n" +
  103.                         "      <spec name="ram">6GB</spec>\n" +
  104.                         "      <spec name="camera">12MP dual camera</spec>\n" +
  105.                         "    </specifications>\n" +
  106.                         "  </product>\n" +
  107.                         "  <product id="p002" category="electronics">\n" +
  108.                         "    <name>Laptop</name>\n" +
  109.                         "    <description>Powerful laptop for professionals</description>\n" +
  110.                         "    <price currency="USD">1299.99</price>\n" +
  111.                         "    <stock>25</stock>\n" +
  112.                         "    <specifications>\n" +
  113.                         "      <spec name="display">15.6 inch Full HD</spec>\n" +
  114.                         "      <spec name="storage">512GB SSD</spec>\n" +
  115.                         "      <spec name="ram">16GB</spec>\n" +
  116.                         "      <spec name="processor">Intel Core i7</spec>\n" +
  117.                         "    </specifications>\n" +
  118.                         "  </product>\n" +
  119.                         "</catalog>";
  120.       
  121.       String outputXml = transformProductCatalog(inputXml);
  122.       System.out.println(outputXml);
  123.     } catch (Exception e) {
  124.       e.printStackTrace();
  125.     }
  126.   }
  127. }
复制代码
  1. from xml.dom.minidom import parseString, Document
  2. def transform_product_catalog(input_xml_string):
  3.     # 解析输入XML
  4.     input_doc = parseString(input_xml_string)
  5.    
  6.     # 创建输出XML文档
  7.     output_doc = Document()
  8.    
  9.     # 创建根元素并添加命名空间
  10.     product_list = output_doc.createElementNS("http://www.example.com/products", "productList")
  11.     output_doc.appendChild(product_list)
  12.    
  13.     # 获取所有产品节点
  14.     products = input_doc.getElementsByTagName("product")
  15.    
  16.     # 遍历每个产品
  17.     for i in range(products.length):
  18.         input_product = products.item(i)
  19.         
  20.         # 创建产品节点
  21.         output_product = output_doc.createElementNS("http://www.example.com/products", "product")
  22.         
  23.         # 设置属性
  24.         output_product.setAttribute("sku", input_product.getAttribute("id"))
  25.         output_product.setAttribute("type", input_product.getAttribute("category"))
  26.         
  27.         # 添加子元素
  28.         name = input_product.getElementsByTagName("name")[0]
  29.         title = output_doc.createElementNS("http://www.example.com/products", "title")
  30.         title.appendChild(output_doc.createTextNode(name.firstChild.data))
  31.         output_product.appendChild(title)
  32.         
  33.         description = input_product.getElementsByTagName("description")[0]
  34.         details = output_doc.createElementNS("http://www.example.com/products", "details")
  35.         details.appendChild(output_doc.createTextNode(description.firstChild.data))
  36.         output_product.appendChild(details)
  37.         
  38.         price = input_product.getElementsByTagName("price")[0]
  39.         cost = output_doc.createElementNS("http://www.example.com/products", "cost")
  40.         cost.setAttribute("currency", price.getAttribute("currency"))
  41.         cost.appendChild(output_doc.createTextNode(price.firstChild.data))
  42.         output_product.appendChild(cost)
  43.         
  44.         stock = input_product.getElementsByTagName("stock")[0]
  45.         inventory = output_doc.createElementNS("http://www.example.com/products", "inventory")
  46.         inventory.appendChild(output_doc.createTextNode(stock.firstChild.data))
  47.         output_product.appendChild(inventory)
  48.         
  49.         # 处理规格/特性
  50.         specifications = input_product.getElementsByTagName("specifications")[0]
  51.         specs = specifications.getElementsByTagName("spec")
  52.         features = output_doc.createElementNS("http://www.example.com/products", "features")
  53.         
  54.         for j in range(specs.length):
  55.             spec = specs.item(j)
  56.             feature = output_doc.createElementNS("http://www.example.com/products", "feature")
  57.             feature.setAttribute("key", spec.getAttribute("name"))
  58.             feature.appendChild(output_doc.createTextNode(spec.firstChild.data))
  59.             features.appendChild(feature)
  60.         
  61.         output_product.appendChild(features)
  62.         
  63.         # 将产品添加到产品列表
  64.         product_list.appendChild(output_product)
  65.    
  66.     # 返回格式化的XML字符串
  67.     return output_doc.toprettyxml(indent="  ")
  68. # 使用示例
  69. input_xml = """<?xml version="1.0" encoding="UTF-8"?>
  70. <catalog>
  71.   <product id="p001" category="electronics">
  72.     <name>Smartphone</name>
  73.     <description>A high-end smartphone with advanced features</description>
  74.     <price currency="USD">699.99</price>
  75.     <stock>50</stock>
  76.     <specifications>
  77.       <spec name="display">6.1 inch OLED</spec>
  78.       <spec name="storage">128GB</spec>
  79.       <spec name="ram">6GB</spec>
  80.       <spec name="camera">12MP dual camera</spec>
  81.     </specifications>
  82.   </product>
  83.   <product id="p002" category="electronics">
  84.     <name>Laptop</name>
  85.     <description>Powerful laptop for professionals</description>
  86.     <price currency="USD">1299.99</price>
  87.     <stock>25</stock>
  88.     <specifications>
  89.       <spec name="display">15.6 inch Full HD</spec>
  90.       <spec name="storage">512GB SSD</spec>
  91.       <spec name="ram">16GB</spec>
  92.       <spec name="processor">Intel Core i7</spec>
  93.     </specifications>
  94.   </product>
  95. </catalog>"""
  96. output_xml = transform_product_catalog(input_xml)
  97. print(output_xml)
复制代码
  1. using System;
  2. using System.Xml;
  3. public class ProductCatalogTransformer
  4. {
  5.   public static string TransformProductCatalog(string inputXmlString)
  6.   {
  7.     // 解析输入XML
  8.     XmlDocument inputDoc = new XmlDocument();
  9.     inputDoc.LoadXml(inputXmlString);
  10.    
  11.     // 创建输出XML文档
  12.     XmlDocument outputDoc = new XmlDocument();
  13.    
  14.     // 添加命名空间
  15.     XmlNamespaceManager nsManager = new XmlNamespaceManager(outputDoc.NameTable);
  16.     nsManager.AddNamespace("ns", "http://www.example.com/products");
  17.    
  18.     // 创建根元素
  19.     XmlElement productList = outputDoc.CreateElement("ns", "productList", "http://www.example.com/products");
  20.     outputDoc.AppendChild(productList);
  21.    
  22.     // 获取所有产品节点
  23.     XmlNodeList products = inputDoc.SelectNodes("//product");
  24.    
  25.     // 遍历每个产品
  26.     foreach (XmlNode inputProductNode in products)
  27.     {
  28.       XmlElement inputProduct = (XmlElement)inputProductNode;
  29.       
  30.       // 创建产品节点
  31.       XmlElement outputProduct = outputDoc.CreateElement("ns", "product", "http://www.example.com/products");
  32.       
  33.       // 设置属性
  34.       outputProduct.SetAttribute("sku", inputProduct.GetAttribute("id"));
  35.       outputProduct.SetAttribute("type", inputProduct.GetAttribute("category"));
  36.       
  37.       // 添加子元素
  38.       XmlNode nameNode = inputProduct.SelectSingleNode("name");
  39.       XmlElement title = outputDoc.CreateElement("ns", "title", "http://www.example.com/products");
  40.       title.InnerText = nameNode.InnerText;
  41.       outputProduct.AppendChild(title);
  42.       
  43.       XmlNode descriptionNode = inputProduct.SelectSingleNode("description");
  44.       XmlElement details = outputDoc.CreateElement("ns", "details", "http://www.example.com/products");
  45.       details.InnerText = descriptionNode.InnerText;
  46.       outputProduct.AppendChild(details);
  47.       
  48.       XmlNode priceNode = inputProduct.SelectSingleNode("price");
  49.       XmlElement cost = outputDoc.CreateElement("ns", "cost", "http://www.example.com/products");
  50.       cost.SetAttribute("currency", priceNode.Attributes["currency"].Value);
  51.       cost.InnerText = priceNode.InnerText;
  52.       outputProduct.AppendChild(cost);
  53.       
  54.       XmlNode stockNode = inputProduct.SelectSingleNode("stock");
  55.       XmlElement inventory = outputDoc.CreateElement("ns", "inventory", "http://www.example.com/products");
  56.       inventory.InnerText = stockNode.InnerText;
  57.       outputProduct.AppendChild(inventory);
  58.       
  59.       // 处理规格/特性
  60.       XmlNode specificationsNode = inputProduct.SelectSingleNode("specifications");
  61.       XmlNodeList specs = specificationsNode.SelectNodes("spec");
  62.       XmlElement features = outputDoc.CreateElement("ns", "features", "http://www.example.com/products");
  63.       
  64.       foreach (XmlNode specNode in specs)
  65.       {
  66.         XmlElement spec = (XmlElement)specNode;
  67.         XmlElement feature = outputDoc.CreateElement("ns", "feature", "http://www.example.com/products");
  68.         feature.SetAttribute("key", spec.GetAttribute("name"));
  69.         feature.InnerText = spec.InnerText;
  70.         features.AppendChild(feature);
  71.       }
  72.       
  73.       outputProduct.AppendChild(features);
  74.       
  75.       // 将产品添加到产品列表
  76.       productList.AppendChild(outputProduct);
  77.     }
  78.    
  79.     // 格式化输出XML
  80.     outputDoc.PreserveWhitespace = true;
  81.    
  82.     // 创建XML编写器设置
  83.     XmlWriterSettings settings = new XmlWriterSettings();
  84.     settings.Indent = true;
  85.     settings.IndentChars = "  ";
  86.     settings.NewLineOnAttributes = false;
  87.     settings.OmitXmlDeclaration = false;
  88.    
  89.     // 使用StringWriter和XmlWriter来格式化XML
  90.     using (System.IO.StringWriter stringWriter = new System.IO.StringWriter())
  91.     {
  92.       using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
  93.       {
  94.         outputDoc.Save(xmlWriter);
  95.       }
  96.       return stringWriter.ToString();
  97.     }
  98.   }
  99.   
  100.   public static void Main(string[] args)
  101.   {
  102.     string inputXml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
  103. <catalog>
  104.   <product id=""p001"" category=""electronics"">
  105.     <name>Smartphone</name>
  106.     <description>A high-end smartphone with advanced features</description>
  107.     <price currency=""USD"">699.99</price>
  108.     <stock>50</stock>
  109.     <specifications>
  110.       <spec name=""display"">6.1 inch OLED</spec>
  111.       <spec name=""storage"">128GB</spec>
  112.       <spec name=""ram"">6GB</spec>
  113.       <spec name=""camera"">12MP dual camera</spec>
  114.     </specifications>
  115.   </product>
  116.   <product id=""p002"" category=""electronics"">
  117.     <name>Laptop</name>
  118.     <description>Powerful laptop for professionals</description>
  119.     <price currency=""USD"">1299.99</price>
  120.     <stock>25</stock>
  121.     <specifications>
  122.       <spec name=""display"">15.6 inch Full HD</spec>
  123.       <spec name=""storage"">512GB SSD</spec>
  124.       <spec name=""ram"">16GB</spec>
  125.       <spec name=""processor"">Intel Core i7</spec>
  126.     </specifications>
  127.   </product>
  128. </catalog>";
  129.    
  130.     string outputXml = TransformProductCatalog(inputXml);
  131.     Console.WriteLine(outputXml);
  132.   }
  133. }
复制代码

性能优化和最佳实践

性能优化技巧

DOM操作通常是昂贵的,特别是对于大型XML文档。尽量减少DOM操作的次数可以显著提高性能。
  1. // 不好的做法:多次查询DOM
  2. let titles = xmlDoc.getElementsByTagName("title");
  3. for (let i = 0; i < titles.length; i++) {
  4.   let title = titles[i];
  5.   let lang = title.getAttribute("lang");
  6.   console.log(lang);
  7. }
  8. // 好的做法:一次性查询并缓存结果
  9. let titles = xmlDoc.getElementsByTagName("title");
  10. let titleLangs = [];
  11. for (let i = 0; i < titles.length; i++) {
  12.   titleLangs.push(titles[i].getAttribute("lang"));
  13. }
  14. console.log(titleLangs);
复制代码

对于复杂的查询,使用XPath通常比多次DOM遍历更高效。
  1. // 不好的做法:多次DOM遍历
  2. let books = xmlDoc.getElementsByTagName("book");
  3. let expensiveBooks = [];
  4. for (let i = 0; i < books.length; i++) {
  5.   let priceNode = books[i].getElementsByTagName("price")[0];
  6.   let price = parseFloat(priceNode.textContent);
  7.   if (price > 30) {
  8.     expensiveBooks.push(books[i]);
  9.   }
  10. }
  11. // 好的做法:使用XPath
  12. let expensiveBooks = xmlDoc.evaluate('//book[price>30]', xmlDoc, null, XPathResult.ANY_TYPE, null);
  13. let nodes = [];
  14. let node = expensiveBooks.iterateNext();
  15. while (node) {
  16.   nodes.push(node);
  17.   node = expensiveBooks.iterateNext();
  18. }
复制代码

当需要向DOM添加多个节点时,使用DocumentFragment可以减少重绘和回流次数。
  1. // 不好的做法:多次直接添加到DOM
  2. let container = xmlDoc.createElement("container");
  3. for (let i = 0; i < 100; i++) {
  4.   let item = xmlDoc.createElement("item");
  5.   item.setAttribute("id", "item" + i);
  6.   container.appendChild(item);
  7. }
  8. // 好的做法:使用DocumentFragment
  9. let container = xmlDoc.createElement("container");
  10. let fragment = xmlDoc.createDocumentFragment();
  11. for (let i = 0; i < 100; i++) {
  12.   let item = xmlDoc.createElement("item");
  13.   item.setAttribute("id", "item" + i);
  14.   fragment.appendChild(item);
  15. }
  16. container.appendChild(fragment);
复制代码

重复访问相同的属性或节点会增加开销,应该缓存这些值。
  1. // 不好的做法:重复访问相同的属性
  2. let book = xmlDoc.getElementsByTagName("book")[0];
  3. if (book.getAttribute("category") === "fiction") {
  4.   console.log("Fiction book: " + book.getAttribute("category"));
  5. }
  6. // 好的做法:缓存属性值
  7. let book = xmlDoc.getElementsByTagName("book")[0];
  8. let category = book.getAttribute("category");
  9. if (category === "fiction") {
  10.   console.log("Fiction book: " + category);
  11. }
复制代码

根据需求选择最合适的查询方法,例如,如果只需要一个元素,使用querySelector或getElementById比getElementsByTagName更高效。
  1. // 不好的做法:使用getElementsByTagName获取单个元素
  2. let books = xmlDoc.getElementsByTagName("book");
  3. let firstBook = books[0];
  4. // 好的做法:使用querySelector获取单个元素
  5. let firstBook = xmlDoc.querySelector("book");
复制代码

最佳实践

始终对DOM操作进行错误处理,特别是当处理外部来源的XML数据时。
  1. try {
  2.   let xmlDoc = parser.parseFromString(xmlString, "text/xml");
  3.   
  4.   // 检查解析错误
  5.   let parserError = xmlDoc.getElementsByTagName("parsererror")[0];
  6.   if (parserError) {
  7.     throw new Error("XML parsing error: " + parserError.textContent);
  8.   }
  9.   
  10.   // 继续处理XML
  11. } catch (e) {
  12.   console.error("Error processing XML:", e.message);
  13. }
复制代码

当处理带有命名空间的XML时,始终使用支持命名空间的方法。
  1. // 不好的做法:忽略命名空间
  2. let titles = xmlDoc.getElementsByTagName("title");
  3. // 好的做法:使用命名空间
  4. let titles = xmlDoc.getElementsByTagNameNS("http://www.example.com/books", "title");
复制代码

在处理XML数据之前,验证其结构是否符合预期。
  1. function validateXmlStructure(xmlDoc) {
  2.   // 检查必需的元素是否存在
  3.   if (!xmlDoc.getElementsByTagName("bookstore").length) {
  4.     throw new Error("Missing required element: bookstore");
  5.   }
  6.   
  7.   // 检查必需的属性是否存在
  8.   let books = xmlDoc.getElementsByTagName("book");
  9.   for (let i = 0; i < books.length; i++) {
  10.     if (!books[i].hasAttribute("category")) {
  11.       throw new Error("Missing required attribute: category");
  12.     }
  13.   }
  14.   
  15.   return true;
  16. }
  17. try {
  18.   let xmlDoc = parser.parseFromString(xmlString, "text/xml");
  19.   validateXmlStructure(xmlDoc);
  20.   // 继续处理XML
  21. } catch (e) {
  22.   console.error("XML validation error:", e.message);
  23. }
复制代码

根据需求选择合适的XML解析器,例如,对于大型文件,考虑使用SAX或StAX解析器而不是DOM解析器。
  1. // Java示例:使用SAX解析器处理大型XML文件
  2. import org.xml.sax.helpers.DefaultHandler;
  3. import org.xml.sax.Attributes;
  4. import javax.xml.parsers.SAXParser;
  5. import javax.xml.parsers.SAXParserFactory;
  6. import java.io.ByteArrayInputStream;
  7. public class LargeXmlProcessor extends DefaultHandler {
  8.   private StringBuilder currentValue = new StringBuilder();
  9.   
  10.   @Override
  11.   public void startElement(String uri, String localName, String qName, Attributes attributes) {
  12.     currentValue.setLength(0);
  13.    
  14.     if (qName.equals("book")) {
  15.       String category = attributes.getValue("category");
  16.       System.out.println("Processing book with category: " + category);
  17.     }
  18.   }
  19.   
  20.   @Override
  21.   public void characters(char[] ch, int start, int length) {
  22.     currentValue.append(ch, start, length);
  23.   }
  24.   
  25.   @Override
  26.   public void endElement(String uri, String localName, String qName) {
  27.     if (qName.equals("title")) {
  28.       System.out.println("Title: " + currentValue.toString());
  29.     } else if (qName.equals("price")) {
  30.       System.out.println("Price: " + currentValue.toString());
  31.     }
  32.   }
  33.   
  34.   public static void main(String[] args) {
  35.     try {
  36.       SAXParserFactory factory = SAXParserFactory.newInstance();
  37.       SAXParser saxParser = factory.newSAXParser();
  38.       
  39.       LargeXmlProcessor handler = new LargeXmlProcessor();
  40.       
  41.       // 假设xmlString是一个大型XML文件的内容
  42.       saxParser.parse(new ByteArrayInputStream(xmlString.getBytes()), handler);
  43.     } catch (Exception e) {
  44.       e.printStackTrace();
  45.     }
  46.   }
  47. }
复制代码

对于关键业务数据,使用XML Schema进行验证可以确保数据的完整性和正确性。
  1. // Java示例:使用XML Schema验证XML文档
  2. import javax.xml.XMLConstants;
  3. import javax.xml.transform.Source;
  4. import javax.xml.transform.stream.StreamSource;
  5. import javax.xml.validation.*;
  6. import org.xml.sax.SAXException;
  7. import java.io.*;
  8. public class XmlSchemaValidator {
  9.   public static boolean validate(String xmlString, String schemaString) {
  10.     try {
  11.       // 创建SchemaFactory
  12.       SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  13.       
  14.       // 创建Schema
  15.       Source schemaSource = new StreamSource(new StringReader(schemaString));
  16.       Schema schema = factory.newSchema(schemaSource);
  17.       
  18.       // 创建Validator
  19.       Validator validator = schema.newValidator();
  20.       
  21.       // 验证XML文档
  22.       Source xmlSource = new StreamSource(new StringReader(xmlString));
  23.       validator.validate(xmlSource);
  24.       
  25.       return true;
  26.     } catch (SAXException e) {
  27.       System.out.println("Validation error: " + e.getMessage());
  28.       return false;
  29.     } catch (IOException e) {
  30.       System.out.println("IO error: " + e.getMessage());
  31.       return false;
  32.     }
  33.   }
  34.   
  35.   public static void main(String[] args) {
  36.     String xmlString = "<?xml version="1.0" encoding="UTF-8"?>\n" +
  37.                       "<bookstore>\n" +
  38.                       "  <book category="fiction">\n" +
  39.                       "    <title>Harry Potter</title>\n" +
  40.                       "    <author>J.K. Rowling</author>\n" +
  41.                       "    <year>2005</year>\n" +
  42.                       "    <price>29.99</price>\n" +
  43.                       "  </book>\n" +
  44.                       "</bookstore>";
  45.    
  46.     String schemaString = "<?xml version="1.0" encoding="UTF-8"?>\n" +
  47.                          "<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">\n" +
  48.                          "  <xs:element name="bookstore">\n" +
  49.                          "    <xs:complexType>\n" +
  50.                          "      <xs:sequence>\n" +
  51.                          "        <xs:element name="book" maxOccurs="unbounded">\n" +
  52.                          "          <xs:complexType>\n" +
  53.                          "            <xs:sequence>\n" +
  54.                          "              <xs:element name="title" type="xs:string"/>\n" +
  55.                          "              <xs:element name="author" type="xs:string"/>\n" +
  56.                          "              <xs:element name="year" type="xs:gYear"/>\n" +
  57.                          "              <xs:element name="price" type="xs:decimal"/>\n" +
  58.                          "            </xs:sequence>\n" +
  59.                          "            <xs:attribute name="category" type="xs:string" use="required"/>\n" +
  60.                          "          </xs:complexType>\n" +
  61.                          "        </xs:element>\n" +
  62.                          "      </xs:sequence>\n" +
  63.                          "    </xs:complexType>\n" +
  64.                          "  </xs:element>\n" +
  65.                          "</xs:schema>";
  66.    
  67.     boolean isValid = validate(xmlString, schemaString);
  68.     System.out.println("XML is " + (isValid ? "valid" : "invalid"));
  69.   }
  70. }
复制代码

常见问题及解决方案

问题1:XML解析错误

问题描述:在解析XML文档时遇到错误,如格式不正确、编码问题等。

解决方案:
  1. // JavaScript
  2. try {
  3.   let parser = new DOMParser();
  4.   let xmlDoc = parser.parseFromString(xmlString, "text/xml");
  5.   
  6.   // 检查解析错误
  7.   let parserError = xmlDoc.getElementsByTagName("parsererror")[0];
  8.   if (parserError) {
  9.     throw new Error("XML parsing error: " + parserError.textContent);
  10.   }
  11.   
  12.   // 继续处理XML
  13. } catch (e) {
  14.   console.error("Error parsing XML:", e.message);
  15.   // 处理错误或提供默认值
  16. }
复制代码
  1. // Java
  2. try {
  3.   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  4.   DocumentBuilder builder = factory.newDocumentBuilder();
  5.   Document document = builder.parse(new InputSource(new StringReader(xmlString)));
  6.   
  7.   // 继续处理XML
  8. } catch (SAXException e) {
  9.   System.err.println("XML parsing error: " + e.getMessage());
  10.   // 处理错误或提供默认值
  11. } catch (IOException e) {
  12.   System.err.println("IO error: " + e.getMessage());
  13.   // 处理错误或提供默认值
  14. } catch (ParserConfigurationException e) {
  15.   System.err.println("Parser configuration error: " + e.getMessage());
  16.   // 处理错误或提供默认值
  17. }
复制代码

问题2:命名空间处理问题

问题描述:在处理带有命名空间的XML文档时,无法正确获取元素或属性。

解决方案:
  1. // JavaScript
  2. // 创建命名空间解析器
  3. function nsResolver(prefix) {
  4.   var ns = {
  5.     'ns': 'http://www.example.com/namespace'
  6.   };
  7.   return ns[prefix] || null;
  8. }
  9. // 使用命名空间执行XPath查询
  10. let xpathResult = xmlDoc.evaluate('//ns:book', xmlDoc, nsResolver, XPathResult.ANY_TYPE, null);
  11. // 或者使用getElementsByTagNameNS
  12. let books = xmlDoc.getElementsByTagNameNS('http://www.example.com/namespace', 'book');
复制代码
  1. // Java
  2. // 创建命名空间上下文
  3. NamespaceContext nsContext = new NamespaceContext() {
  4.   @Override
  5.   public String getNamespaceURI(String prefix) {
  6.     if (prefix.equals("ns")) {
  7.       return "http://www.example.com/namespace";
  8.     }
  9.     return null;
  10.   }
  11.   @Override
  12.   public String getPrefix(String namespaceURI) {
  13.     return null;
  14.   }
  15.   @Override
  16.   public Iterator<String> getPrefixes(String namespaceURI) {
  17.     return null;
  18.   }
  19. };
  20. // 创建XPath并设置命名空间上下文
  21. XPathFactory xpathFactory = XPathFactory.newInstance();
  22. XPath xpath = xpathFactory.newXPath();
  23. xpath.setNamespaceContext(nsContext);
  24. // 使用命名空间执行XPath查询
  25. XPathExpression expr = xpath.compile("//ns:book");
  26. NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
  27. // 或者使用getElementsByTagNameNS
  28. NodeList nodes = document.getElementsByTagNameNS("http://www.example.com/namespace", "book");
复制代码

问题3:性能问题

问题描述:处理大型XML文档时性能低下,内存占用高。

解决方案:
  1. // Java:使用SAX解析器代替DOM解析器
  2. import org.xml.sax.helpers.DefaultHandler;
  3. import org.xml.sax.Attributes;
  4. import javax.xml.parsers.SAXParser;
  5. import javax.xml.parsers.SAXParserFactory;
  6. import java.io.ByteArrayInputStream;
  7. public class LargeXmlProcessor extends DefaultHandler {
  8.   @Override
  9.   public void startElement(String uri, String localName, String qName, Attributes attributes) {
  10.     // 处理元素开始
  11.   }
  12.   
  13.   @Override
  14.   public void characters(char[] ch, int start, int length) {
  15.     // 处理元素内容
  16.   }
  17.   
  18.   @Override
  19.   public void endElement(String uri, String localName, String qName) {
  20.     // 处理元素结束
  21.   }
  22.   
  23.   public static void main(String[] args) {
  24.     try {
  25.       SAXParserFactory factory = SAXParserFactory.newInstance();
  26.       SAXParser saxParser = factory.newSAXParser();
  27.       
  28.       LargeXmlProcessor handler = new LargeXmlProcessor();
  29.       
  30.       // 处理大型XML文件
  31.       saxParser.parse(new ByteArrayInputStream(xmlString.getBytes()), handler);
  32.     } catch (Exception e) {
  33.       e.printStackTrace();
  34.     }
  35.   }
  36. }
复制代码
  1. # Python:使用iterparse处理大型XML文件
  2. from xml.etree.ElementTree import iterparse
  3. def process_large_xml(file_path):
  4.     # 获取迭代器
  5.     context = iterparse(file_path, events=("start", "end"))
  6.    
  7.     # 获取根元素
  8.     event, root = next(context)
  9.    
  10.     for event, elem in context:
  11.         if event == "end" and elem.tag == "book":
  12.             # 处理book元素
  13.             category = elem.get("category")
  14.             title = elem.find("title").text
  15.             print(f"Processing book: {title}, Category: {category}")
  16.             
  17.             # 清理已处理的元素以节省内存
  18.             root.clear()
  19.    
  20.     # 关闭文件
  21.     if hasattr(context, 'close'):
  22.         context.close()
  23. # 使用示例
  24. process_large_xml("large_books.xml")
复制代码

问题4:特殊字符处理

问题描述:XML中的特殊字符(如<, >, &, “, ‘)导致解析错误。

解决方案:
  1. // JavaScript:转义XML特殊字符
  2. function escapeXml(unsafe) {
  3.   return unsafe.replace(/[<>&'"]/g, function(c) {
  4.     switch (c) {
  5.       case '<': return '&lt;';
  6.       case '>': return '&gt;';
  7.       case '&': return '&amp;';
  8.       case '\'': return '&apos;';
  9.       case '"': return '&quot;';
  10.     }
  11.   });
  12. }
  13. // 使用示例
  14. let unsafeText = "This is a <test> & 'example'";
  15. let safeText = escapeXml(unsafeText);
  16. console.log(safeText); // 输出: This is a &lt;test&gt; &amp; &apos;example&apos;
复制代码
  1. // Java:转义XML特殊字符
  2. import org.apache.commons.text.StringEscapeUtils;
  3. public class XmlUtils {
  4.   public static String escapeXml(String unsafe) {
  5.     return StringEscapeUtils.escapeXml11(unsafe);
  6.   }
  7.   
  8.   public static void main(String[] args) {
  9.     String unsafeText = "This is a <test> & 'example'";
  10.     String safeText = escapeXml(unsafeText);
  11.     System.out.println(safeText); // 输出: This is a &lt;test&gt; &amp; 'example'
  12.   }
  13. }
复制代码

问题5:XPath查询失败

问题描述:XPath查询无法找到预期的元素或属性。

解决方案:
  1. // JavaScript:调试XPath查询
  2. function debugXPath(xmlDoc, xpath) {
  3.   try {
  4.     let result = xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE, null);
  5.     let nodes = [];
  6.     let node = result.iterateNext();
  7.     while (node) {
  8.       nodes.push(node);
  9.       node = result.iterateNext();
  10.     }
  11.    
  12.     console.log(`XPath "${xpath}" found ${nodes.length} nodes:`);
  13.     nodes.forEach((node, index) => {
  14.       console.log(`Node ${index + 1}: ${node.nodeName} (type: ${node.nodeType})`);
  15.       if (node.nodeType === Node.ELEMENT_NODE) {
  16.         console.log(`  Attributes: ${node.attributes.length}`);
  17.         for (let i = 0; i < node.attributes.length; i++) {
  18.           console.log(`    ${node.attributes[i].name}: ${node.attributes[i].value}`);
  19.         }
  20.       } else if (node.nodeType === Node.ATTRIBUTE_NODE) {
  21.         console.log(`  Value: ${node.value}`);
  22.       } else if (node.nodeType === Node.TEXT_NODE) {
  23.         console.log(`  Content: ${node.textContent.trim()}`);
  24.       }
  25.     });
  26.    
  27.     return nodes;
  28.   } catch (e) {
  29.     console.error(`Error evaluating XPath "${xpath}": ${e.message}`);
  30.     return [];
  31.   }
  32. }
  33. // 使用示例
  34. let xmlDoc = parser.parseFromString(xmlString, "text/xml");
  35. debugXPath(xmlDoc, '//book[@category="fiction"]/title');
复制代码
  1. // Java:调试XPath查询
  2. import javax.xml.xpath.*;
  3. import org.w3c.dom.*;
  4. public class XPathDebugger {
  5.   public static NodeList debugXPath(Document document, String xpath) {
  6.     try {
  7.       XPathFactory xpathFactory = XPathFactory.newInstance();
  8.       XPath xpathObj = xpathFactory.newXPath();
  9.       
  10.       XPathExpression expr = xpathObj.compile(xpath);
  11.       NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
  12.       
  13.       System.out.println("XPath "" + xpath + "" found " + nodes.getLength() + " nodes:");
  14.       for (int i = 0; i < nodes.getLength(); i++) {
  15.         Node node = nodes.item(i);
  16.         System.out.println("Node " + (i + 1) + ": " + node.getNodeName() + " (type: " + node.getNodeType() + ")");
  17.         
  18.         if (node.getNodeType() == Node.ELEMENT_NODE) {
  19.           Element element = (Element) node;
  20.           NamedNodeMap attributes = element.getAttributes();
  21.           System.out.println("  Attributes: " + attributes.getLength());
  22.           for (int j = 0; j < attributes.getLength(); j++) {
  23.             Node attr = attributes.item(j);
  24.             System.out.println("    " + attr.getNodeName() + ": " + attr.getNodeValue());
  25.           }
  26.         } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
  27.           System.out.println("  Value: " + node.getNodeValue());
  28.         } else if (node.getNodeType() == Node.TEXT_NODE) {
  29.           System.out.println("  Content: " + node.getTextContent().trim());
  30.         }
  31.       }
  32.       
  33.       return nodes;
  34.     } catch (XPathExpressionException e) {
  35.       System.err.println("Error evaluating XPath "" + xpath + "": " + e.getMessage());
  36.       return null;
  37.     }
  38.   }
  39.   
  40.   public static void main(String[] args) {
  41.     try {
  42.       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  43.       DocumentBuilder builder = factory.newDocumentBuilder();
  44.       Document document = builder.parse(new InputSource(new StringReader(xmlString)));
  45.       
  46.       debugXPath(document, "//book[@category='fiction']/title");
  47.     } catch (Exception e) {
  48.       e.printStackTrace();
  49.     }
  50.   }
  51. }
复制代码

总结

XML DOM属性获取技术是处理XML文档的核心技能,它为开发者提供了强大的工具来访问、操作和转换XML数据。本文从基础语法到高级应用,全面解析了XML DOM属性获取技术的各个方面。

我们首先介绍了XML DOM的基础概念,包括DOM树结构和节点类型,然后详细讲解了DOM属性获取的基础语法和常用方法。通过丰富的代码示例,我们展示了如何在不同编程语言中获取、设置和删除XML元素的属性。

节点遍历技术是DOM操作的重要组成部分,我们讨论了如何访问父子节点、兄弟节点,以及如何高效地查找特定节点。在高级应用部分,我们深入探讨了XPath查询、命名空间处理和属性值转换等高级技术,这些技术能够帮助开发者解决复杂的数据访问难题。

通过实际应用案例,我们展示了如何将XML DOM属性获取技术应用于配置文件解析和数据转换等实际场景。此外,我们还提供了性能优化技巧和最佳实践,帮助开发者编写更高效、更可靠的XML处理代码。

最后,我们讨论了开发者在使用XML DOM时可能遇到的常见问题,并提供了相应的解决方案。这些解决方案涵盖了XML解析错误、命名空间处理、性能问题、特殊字符处理和XPath查询失败等方面。

掌握XML DOM属性获取技术对于现代软件开发至关重要,它不仅能够帮助开发者高效地处理XML数据,还能够解决复杂的数据访问难题。通过本文的学习,开发者应该能够深入理解XML DOM的工作原理,并能够灵活运用各种技术来处理XML文档。

随着数据交换和集成需求的不断增长,XML作为一种通用的数据格式将继续发挥重要作用。因此,深入理解和掌握XML DOM属性获取技术将为开发者在数据处理和系统集成领域提供强大的竞争优势。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则