0

我将 HTML 加载到HTMLdocument中。现在我想使用属于dt的每个dd访问/选择每个dt并将其存储在一个数组中以供以后使用。我已经尝试过http://www.w3schools.com/xsl/xpath_axes.asp中提到的 XPath 语法,但它根本不起作用。我刚收到一个。但是我做错了什么?NullReferenceException

请记住,有时 1 有 2 个或多个**dd**元素**dt**。我想将每个**dd**元素添加到相应的**dt**.

提前谢谢了。

<dl>
  <dt id="one">one</dt>
  <dd>some text</dd>
  <dt id="two">two</dt>
  <dd>some text</dd>
  <dt id="three">three</dt>
  <dd>some text</dd>
  <dd>some text</dd>
  <dt id="four">four</dt>
  <dd>some text</dd>
  and so on...
</dl>
4

1 回答 1

0

dt和元素之间没有直接联系dd,这就是为什么我个人没有找到使用 XPath 为您提供解决方案的方法。XSLT 可能是一种选择,但是,我也没有找到使用 XSLT 的快速简便的方法。由于您使用 C#,因此我制作了一个快速原型函数,说明它在 C# 中的外观:

public static void Main(string[] args)
        {            
            Dictionary<string, List<string>> dt = new Dictionary<string, List<string>>();        

            using(XmlReader reader = XmlReader.Create(@"data.xml")){
                bool incomingDd = false;
                while(reader.Read()){
                    switch(reader.NodeType){
                        case XmlNodeType.Element:                            
                            if(String.Equals(reader.Name, "dt", StringComparison.OrdinalIgnoreCase)){
                                dt.Add(reader.GetAttribute("id"), new List<string>());
                            }
                            else if(String.Equals(reader.Name, "dd", StringComparison.OrdinalIgnoreCase)){
                                incomingDd = true;                                
                            }
                            break;

                        case XmlNodeType.Text:                                
                            if(incomingDd && !String.IsNullOrEmpty(reader.Value)){                                
                                dt.Values.ElementAt(dt.Count -1).Add(reader.Value);
                                incomingDd = false;
                            }
                            break;
                    }
                }
            }

            foreach(var item in dt){
                Console.WriteLine($"{item.Key} {item.Value.Count()}:");
                foreach(var dd in item.Value){
                    System.Console.WriteLine($"\t{dd}");
                }
            }
        }

这可能不是满足您需求的最漂亮的代码,但这应该让您了解如何解决您的问题。

于 2016-09-19T14:36:43.610 回答