无法使用LINQ to XML读取XML注释

时间:2015-03-31 23:22:12

标签: c# xml linq linq-to-xml

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

<?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
        });

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

试试这个:

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>()),
        });

答案 1 :(得分:1)

我在此链接中找到了解决方案: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()
                                                                )
        });