Save specific nodes when using LINQ to XML

I'm having difficulty saving certain nodes (in this case <b>) when parsing XML with LINQ to XML. First I will take node with the following LINQ query ...

IEnumerable<XElement> node = from el in _theData.Descendants("msDict") select el;

Which returns the following XML (like the first XElement) ...

<msDict lexid="m_en_us0000002.001" type="core">
  <df>(preceding a numeral) <b>pound</b> or <b>pounds</b> (of money)
  <genpunc tag="df">.</genpunc></df>
</msDict>

Then I collect the contents with the following code ...

StringBuilder output = new StringBuilder();
foreach (XElement elem in node)
{
    output.append(elem.Value);
}

Here is the fault point. All XML nodes are deleted, but I want to keep all instances <b>. I expect to get the following as a result ...

(preceding a numeral) <b>pound</b> or <b>pounds</b> (of money).

Note. I know this is a simple operation in XSLT, but I would like to know if there is an easy way to do this using LINQ to XML.

+3
source share
1 answer

" , , , ":

StringBuilder output = new StringBuilder();  
foreach (XElement elem in node)  
{  
    output.append(string.Join("", elem.Nodes().Select(n => n.ToString()).ToArray()));  
} 

, XElement...

UPDATE: , <b> node.

:

StringBuilder output = new StringBuilder();
foreach (XElement elem in node)
{
    output.Append(stripTags(elem));
}

stripTags:

private static string stripTags(XNode node)
{
    if (node is XElement && !((XElement)node).Name.ToString().Equals("b", StringComparison.InvariantCultureIgnoreCase))
    {
        return string.Join(string.Empty, ((XElement)node).Nodes().Select(n => stripTags(n)).ToArray());
    }
    else
    {
        return node.ToString();
    }
}

, : , , LINQ to XML, ...

+3

Source: https://habr.com/ru/post/1771815/


All Articles