c# - 如何使用 linq-to-xml 更改标签名称和获取属性

标签 c# linq linq-to-xml

这是我的xml文件

<tag>
    <ImageObject Color="BlackWhite" FileRef="12.gif" Format="GIF" Rendition="HTML" Type="Linedraw" />
    <ImageObject Color="BlackWhite" FileRef="32.gif" Format="GIF" Rendition="HTML" Type="Linedraw"/>
    <ImageObject Color="BlackWhite" FileRef="3.gif" Format="GIF" Rendition="HTML" Type="Linedraw"/>
</tag>

输出结果与此类似

<tag>
    <img src="12.gif" />
    <img src="32.gif" />
    <img src="3.gif" />
</tag>

到目前为止,这是我的代码。但我无法设置 img 的属性,因为我不知道如何检索 fileref 的属性

XElement rootImg = XElement.Parse(xml string variable);

IEnumerable<XElement> img =
    from el in rootImg.Descendants("ImageObject").ToList()
    where (string)el.Attribute("Format") != ""
    select el;

foreach (XElement el in img)
{
    el.Name = "img";
    el.RemoveAttributes();
    el.SetAttributeValue("src", "");
}

最佳答案

此时没有属性 - 它已从上面的一行中删除。相反,您可以使用以下内容:

foreach (XElement el in img)
{
    var fileRef = el.Attribute("FileRef");
    el.Name = "img";
    el.RemoveAttributes();
    el.SetAttributeValue("src", fileRef.Value);
}

关于c# - 如何使用 linq-to-xml 更改标签名称和获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38843588/

相关文章:

c# - 正则表达式:将驼峰大小写转换为带下划线的所有大写

c# - Linq-to-SQL:如何对子选择执行计数

c# - 日期时间如何工作以及如何在 Windows 窗体 ADO 实体中比较两个日期?

c# - 如何通过 LINQ to XML 创建 Dictionary<int, string>?

c# - 循环遍历 XDocument 的元素并获取特定属性

c# - 无法使用 PostgreSQL 配置 AspNet.Identity

c# - 显示EMF文件

c# - 将 Expression<Func<DTOUser, bool>> 谓词转换为 Expression<Func<User, bool>> 谓词

c# - LINQ 或 lambda 表达式中的比较字符串之间的子句等效于什么?

vb.net - 条件 XML 文字