这是我的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/