代码之家  ›  专栏  ›  技术社区  ›  Priyank Bolia

从LINQ中的字符串创建XML子树?

  •  1
  • Priyank Bolia  · 技术社区  · 16 年前

    我想使用C中的一些函数修改所有文本节点。 我想插入从某个字符串创建的另一个XML子树。

    例如,我想更改这个

    <root>
    this is a test
    </root>
    

    <root>
    this is <subtree>another</subtree> test
    </root>
    

    我有这段代码,但是它插入了文本节点,我想创建XML子树并插入它,而不是纯文本节点。

    List<XText> textNodes = element.DescendantNodes().OfType<XText>().ToList();
    foreach (XText textNode in textNodes)
    {
        String node = System.Text.RegularExpressions.Regex.Replace(textNode.Value, "a", "<subtree>another</subtree>");
        textNode.ReplaceWith(new XText(node));
    } 
    
    2 回复  |  直到 16 年前
        1
  •  2
  •   Jonatan Lindén    16 年前

    可以将原始的xtext节点拆分为多个节点,并在其中添加Xelement。然后将原始节点替换为三个新节点。

    List<XNode> newNodes = Regex.Split(textNode.Value, "a").Select(p => (XNode) new XText(p)).ToList();
    
    newNodes.Insert(1, new XElement("subtree", "another")); // substitute this with something better
    
    textNode.ReplaceWith(newNodes);
    
        2
  •  0
  •   Priyank Bolia    16 年前

    我猜 CreateDocumentFragment 虽然不是LINQ,但使用LINQ的想法很简单。