【问题标题】:Xml node not actually node, need to get attributexml节点不是实际节点,需要获取属性
【发布时间】:2015-08-06 19:39:45
【问题描述】:

这里是xml:

<_text_column min_width="0" max_width="2031051">
    <PF_Para_Base align="center">
        <_char data_tag="PricesGoodText" font_size="35270" bold="true" italic="false" font_name="/ITC Franklin Gothic Demi" text_color="White">PricesGoodText</_char>
    </PF_Para_Base>
</_text_column>

我正在打开文件并将根目录附加到文件中,因为文件出现多根错误

using (var fs = new StreamReader(fullFileName))
using (var xr = XmlReader.Create(fs, settings))
{
    while (xr.Read())
    {
        if (xr.NodeType == XmlNodeType.Element)
        {
            rootElement.Add(XElement.Load(xr.ReadSubtree()));
        }
    }
}

var attr = rootElement.Elements("char").Attribute("data_tag");

我需要从节点_char 中获取属性data_tag。它以null 的形式返回。

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    rootElement.Elements("_char").Attributes("data_tag"); 是错误的,因为Elements 只读取直接子级,你应该使用Descendants

    rootElement.Descendants("_char").Select(c => c.Attribute("data_tag").Value); 
    

    检查这个 SO 问题:What is the difference between Linq to XML Descendants and Elements

    【讨论】:

    • 呃...简单的解决方案是最难发现的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多