如何用Go 1.19读取XML文件中的处理指令属性值
用Go 1.19读取XML自定义处理指令的属性值
给定包含自定义处理指令的XML文件,需要提取<?ID Object="AUTO_REPORT_OBJECT" Version="1.0"?>中的Object和Version属性值,使用Go 1.19版本实现。
XML示例内容:
<?xml version="1.0" encoding="UTF-8"?><?ID Object="AUTO_REPORT_OBJECT" Version="1.0"?><?xml-stylesheet type="text/xsl" href="../XML/ProdRep.xsl"?><!DOCTYPE Auto_Report SYSTEM "../XML/ProdRep.dtd" [ <!ELEMENT Auto_Report (Production_Report+)> ]><Auto_Report> <Production_Report Type="AUTO"> ... more tags </Production_Report></Auto_Report><?End?>
解决方案
Go标准库的encoding/xml提供的Decoder可以遍历XML的所有Token,其中处理指令对应xml.ProcessingInstruction类型。我们可以通过遍历Token找到目标处理指令,再解析其内容中的属性。
代码实现
package main import ( "encoding/xml" "fmt" "os" "strings" ) func main() { // 替换为你的XML文件路径 file, err := os.Open("your_report.xml") if err != nil { fmt.Printf("打开文件失败: %v\n", err) return } defer file.Close() decoder := xml.NewDecoder(file) for { token, err := decoder.Token() if err != nil { break // 读取结束或出错时退出循环 } // 判断当前Token是否为处理指令 pi, ok := token.(xml.ProcessingInstruction) if !ok { continue } // 定位到目标ID处理指令 if pi.Target == "ID" { props := parsePIAttributes(pi.Instruction) fmt.Printf("Object: %s\n", props["Object"]) fmt.Printf("Version: %s\n", props["Version"]) break // 找到目标后可提前终止遍历 } } } // 解析处理指令内容中的键值对属性 func parsePIAttributes(content string) map[string]string { props := make(map[string]string) parts := strings.Fields(content) for _, part := range parts { kv := strings.SplitN(part, "=", 2) if len(kv) != 2 { continue } key := kv[0] // 去除属性值的前后引号 value := strings.Trim(kv[1], "\"") props[key] = value } return props }
代码说明
- 使用
xml.Decoder.Token()遍历XML的所有节点,包括声明、处理指令、DOCTYPE、元素等 - 识别
xml.ProcessingInstruction类型的Token,通过Target字段定位到自定义的ID处理指令 - 自定义
parsePIAttributes函数,将处理指令的内容按空格分割,拆分键值对并去除引号,最终返回属性映射
注意事项
- 该方式无需加载整个XML文件到内存,适合处理大体积XML
- 如果属性值包含空格,需要修改解析逻辑(比如使用扫描器处理带引号的完整字符串)
内容的提问来源于stack exchange,提问作者marchiosim
相关产品推荐
相关产品推荐

