XML含有命名空间时候的解析

今天解析一个build自动生成的xml,按照以前的解析方法发现找不到节点。
后来发现时因为它的xml里面有命名空间,就是xmlns=…………

这个时候的解析有两点要注意,我用的是C#进行解析。

1. 要把命名空间加载进来。
2. xpath不能再用/分隔了,需要用/ns:

话不多说,上段code,一看就懂:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public static ArrayList GetSourceFileNames(String filePath)
         {
            ArrayList names = new ArrayList();
            try
            {
                XmlDocument xml = new XmlDocument();
                xml.Load(filePath);
                XmlElement root = xml.DocumentElement;
                String nameSpace = root.NamespaceURI;
                Console.WriteLine(nameSpace + "!!");
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);
                nsmgr.AddNamespace("ns", nameSpace);
 
                XmlNodeList nodelist = root.SelectNodes("/ns:Project/ns:test", nsmgr);
                for (int i = 0; i < nodelist.Count; i++)
                {
                    Console.WriteLine(nodelist[i].InnerText);
                    names.Add(nodelist[i].InnerText);
                }
 
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception description:" + e.Message + ". Something wrong when finding xml's node during code coverage process.");
                FileUtil.WriteLog("Exception description:" + e.Message + ". Something wrong when finding xml's node during code coverage process.");
            }
 
            return names;
        }
此条目发表在 C# 分类目录,贴了 , 标签。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>