在C

做几个笔记

[En]

Take a few notes

文件后缀不必是.xml。它可以是任何后缀,只要内容符合XML和格式,就可以进行解析。

[En]

The file suffix does not have to be .xml. It can be any suffix, and can be parsed as long as the content conforms to xml and format.

文件编码需要是utf-8,python和c#都需要,或者xml文件头有这样一句: <?xml version="1.0" encoding="utf-8"?>

对于一些比较复杂的文件,从上到下按照节点进行解析比较麻烦,但是通过XPath进行解析并指定节点要方便得多。

[En]

For some more complex files, it is troublesome to parse according to the node from top to bottom, but it is much more convenient to parse through xpath and specify the node.

xml文件示例


            江南

                    桃溪
                    jiangnan/forest_05
                    Zone/xxxx1

                    木渎镇
                    jiangnan/muduzheng
                    Jn_2/xxxx2

            Space/Jiangnan_xxx
            function/amb_wind

C#版本解析

重要的点就是通过 node.SelectSingleNode来选择要的节点。

var xmldoc = new XmlDocument();
var xmlReader = XmlReader.Create(def_path);
xmldoc.Load(xmlReader);
var nodeList = xmldoc.FirstChild.ChildNodes;
Console.WriteLine($"读入xml,节点数:{nodeList.Count}");
StringBuilder builder = new StringBuilder();
builder.AppendLine($"场景chunk名称,音乐名,环境底噪,所属大区"); //场景chunk名称 文件夹名 资源名

foreach (XmlNode node in nodeList)
{
    if (node.Name != "space")
    {
        Console.WriteLine("遇到特殊节点,未解析");
        continue;
    }
    var subzone = node.SelectSingleNode("subzone");
    var name = node.SelectSingleNode("name");
    var music = node.SelectSingleNode("music");
    var ambient = node.SelectSingleNode("ambient");

    //....处理第1层节点的数据

    if (subzone != null)
    {
        var zones = subzone.ChildNodes;
        foreach (XmlLinkedNode ccNode in zones)
        {
            var name1 = ccNode.SelectSingleNode("name");
            var music1 = ccNode.SelectSingleNode("music");
            var ambient1 = ccNode.SelectSingleNode("ambient");
            var subzone1 = ccNode.SelectSingleNode("subzone");
            //..... 处理第2层节点的数据
            //note 如果还有子子节点的话,需要再次处理
            if (subzone1 != null)
            {
                Console.WriteLine($"第2层之后还有subzone, name:{tunkName} ,未解析");
            }
        }
    }
}

python版本解析

示例:

[En]

Example:

import xml.etree.ElementTree as ET
if __name__ == '__main__':
    xml_path = r"D:\xxx\scene.xml"
    tree = ET.parse(xml_path)
    root = tree.getroot()
    for child in root:
        childs = child.getchildren()
        print(childs,child.tag,child.text)
        if child.tag == "space" and child.text and child.text:
            pass

Original: https://www.cnblogs.com/zhaoqingqing/p/15892931.html
Author: 或python中使用xpath解析xml
Title: 在C

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/6394/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

最近整理资源【免费获取】:   👉 程序员最新必读书单  | 👏 互联网各方向面试题下载 | ✌️计算机核心资源汇总