无法使用 LINQ to XML 读取 XML 评论

Cannot read XML comments using LINQ to XML

我无法检索 XML 节点评论。有没有不同的方法来检索它? .Value 也不起作用。我在 Whosebug 中找不到任何东西。 这就是我正在做的事情:

<?xml version="1.0" encoding="utf-8"?>
<components>
    <component name="AAA">
        <sample>
            <!-- blah blah blah --> 
        </sample>
        <data>
            <!-- blah blah blah -->             
        </data>
    </component>

    <component name="BBB">
        <sample>
            <!-- blah blah blah --> 
        </sample>
        <data>
            <!-- blah blah blah -->             
        </data>     
    </component>    
</components>

public class Component
{
    public string Name { get; set; }
    public string Sample { get; set; }
    public string Data { get; set; }
}

    XDocument doc = XDocument.Load(xmlFileName);

    Component components = doc.Descendants("component")
        .Select(x => new Component
        {
            Name = (string)x.Attribute("name"),
            Sample = (string)x.Element("sample"), //cannot read value
            Data = (string)x.Element("data") //cannot read value
        });

有什么想法吗?

试试这个:

var components =
    doc
        .Descendants("component")
        .Select(x => new Component()
        {
            Name = (string)x.Attribute("name"),
            Sample = String.Join("", x.Element("sample").Nodes().OfType<XComment>()),
            Data = String.Join("", x.Element("data").Nodes().OfType<XComment>()),
        });

我在这个 link 中找到了解决方案:https://msdn.microsoft.com/en-us/library/bb675167.aspx 所以代码最终看起来像这样:

    var components = doc
        .Descendants("component")
        .Select(x => new Component()
        {
            Name = (string)x.Attribute("name"),
            Sample = x.Element("sample").Nodes().OfType<XComment>()
                                                                .Select(s=>s.Value)
                                                                .Aggregate(
                                                                    new StringBuilder(), 
                                                                    (s,i)=>s.Append(i),
                                                                    s => s.ToString()
                                                                ),
            Data = x.Element("data").Nodes().OfType<XComment>()
                                                                .Select(s=>s.Value)
                                                                .Aggregate(
                                                                    new StringBuilder(), 
                                                                    (s,i)=>s.Append(i),
                                                                    s => s.ToString()
                                                                )
        });