2016-09-19 24 views
0

我将HTML加载到HTML文档中。现在我想要访问/选择每个dt与属于dt的每个dd,并将其存储在数组中供以后使用。我已经尝试了http://www.w3schools.com/xsl/xpath_axes.asp中提到的XPath语法,但它没有任何作用。我刚收到NullReferenceException。但是我做错了什么?如何使用敏捷包从HTML文档访问当前节点和后代?

请注意,有时候一个**dt**有两个或更多个**dd**元素。我想将每个**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> 

回答

0

还有就是dtdd元素之间没有直接的联系,这就是为什么我个人没有找到一种方法,为您提供使用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}"); 
       } 
      } 
     } 

这可能不是适合你的需求的最漂亮的代码,但是这应该给你的是如何解决的想法你的问题。

+0

嗨codeguy,我最深的歉意为我迟到的回应,但我在上周很忙。非常感谢您的回答。这对我帮助很大! –

+0

没问题,乐意帮忙!如果是问题的解决方案,您能否将其标记为答案?谢谢。 – codeguy