使用linq获取父节点的文本除子节点文本外

时间:2015-07-23 05:52:14

标签: c# xml linq

<para>Scales to meet individual data privacy requirements
<ul class="listbullet2">
<li class="listbullet2">Server counts up to 25,000</li>
<li class="listbullet2">Millions of drives</li>
<li class="listbullet2">Millions of encryption keys</li>
</ul>
</para>

电流输出: -

<para>Scales to meet individual data privacy requirements Server counts up to 25,000Millions of drivesMillions of encryption keys</para> 

必需输出: -

 <para>Scales to meet individual data privacy requirements <li>Server counts up to 25,000</li> <li>Millions of drives</li> <li>Millions of encryption keys</li> </para>

我们需要获取文本“Scales以满足个人数据隐私要求”,目前它正在为我提供完整的内容。谁能告诉代码?

3 个答案:

答案 0 :(得分:0)

虽然你的样本看起来像是一个html,但这里有一个Linq2Xml的解决方案

var xDoc = XDocument.Parse(xmlstring);
xDoc.Root.Elements().Remove();
var txt = xDoc.Root.Value; //=>Scales to meet individual data privacy requirements

答案 1 :(得分:0)

另一个有效的Linq to XML解决方案:

XElement elem = XElement.Parse(xml);
var res = elem.Nodes().OfType<XText>().FirstOrDefault().Value;

Console.WriteLine(res); // Scales to meet individual data privacy requirements

答案 2 :(得分:0)

尝试替换

 XDocument doc = XDocument.Parse(input);
            foreach (XElement para in doc.Descendants("para"))
            {
                para.ReplaceNodes(para.Descendants("li"));
            }​