Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从LINQ中的字符串创建XML子树?_C#_Xml_Linq - Fatal编程技术网

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

C# 从LINQ中的字符串创建XML子树?,c#,xml,linq,C#,Xml,Linq,我想使用C中的一些函数修改所有文本节点。 我想插入从某个字符串创建的另一个xml子树 例如,我想改变这个 <root> this is a test </root> 到 我有这段代码,但它插入文本节点,我想创建xml子树并插入它,而不是纯文本节点 List<XText> textNodes = element.DescendantNodes().OfType<XText>().ToList(); foreach (XText textNode i

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

例如,我想改变这个

<root>
this is a 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));
} 

可以将原始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);

我想这要容易得多,虽然不是LINQ,但使用LINQ的想法很简单。

可能有很多“a”和“另一个”,而“a”不是常数,“另一个”的值也取决于“a”的值。是否有更好的解决方案,我可以从字符串创建一个子节点。同样,这是错误的,如果没有“a”,那么您将在其中插入一个“另一个”。此外,这不会编译,因为不会从“System.Collections.Generic.List”到“System.Collections.Generic.List”进行类型转换。我也找不到insert方法。是的,插入并不是注释的方式,但它只是向集合中添加一个XElement,然后用一个新节点集合替换旧节点。我忘记了一个演员阵容,这就是为什么它不起作用,所以现在应该可以了。找不到Insert方法是什么意思?它是列表类的成员。
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);