如何使用 linq-to-xml 更改标签名称和获取属性
How to change tag name and get attribute using 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);
}
首先创建 XElement 对象并解析 XML 文件,然后将 Enumerable (img) 的对象作为 el 找到 formate,现在编写 foreach 循环以从 img (IEnumrable) 和 setAttributeValue 获取属性。最后你的代码看起来像。
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)
{
var fileRef = el.Attribute("FileRef");
el.Name = "img";
el.RemoveAttributes();
el.SetAttributeValue("src", fileRef.Value);
}
这是我的 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);
}
首先创建 XElement 对象并解析 XML 文件,然后将 Enumerable (img) 的对象作为 el 找到 formate,现在编写 foreach 循环以从 img (IEnumrable) 和 setAttributeValue 获取属性。最后你的代码看起来像。
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)
{
var fileRef = el.Attribute("FileRef");
el.Name = "img";
el.RemoveAttributes();
el.SetAttributeValue("src", fileRef.Value);
}