Jay*_*Jay 4 c# xml string linq-to-xml
假设有一个xml文件,如下所示:
<Instances>
<Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image1.jpg" ImageNumber = "1"/>
<Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image2.jpg" ImageNumber = "2"/>
<Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image3.jpg" ImageNumber = "3"/>
<Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image4.jpg" ImageNumber = "4"/>
<Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image5.jpg" ImageNumber = "5"/>
</Instances>
Run Code Online (Sandbox Code Playgroud)
此xml文件作为字符串读取并传递给函数.此xml文件包含有关特定图像文件的信息.我想从这个字符串中提取所有图像文件的位置.因此无论"位置"提交的价值如何,我都需要收集所有这些价值.在C#中实现这一目标的最佳方法是什么?
谢谢,
Jon*_*eet 17
最简单的方法:将其解析为XML(我建议使用LINQ to XML),然后使用XML API添加信息.将它作为原始字符数据自己处理是没有意义的.
样品:
XElement root = XElement.Parse(text);
List<string> images = root.Elements("Bits")
.Select(x => (string) x.Attribute("Location"))
.ToList();
Run Code Online (Sandbox Code Playgroud)
(这将为任何Bits不包含Location属性的元素赋予null .)
请注意,此处的结构不是XElement.Parse的有效XML,因为您的元素没有名称,只有属性.
一个可能正确的结构是:
<Instances>
<Image Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image1.jpg" ImageNumber = "1" />
<Image Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image2.jpg" ImageNumber = "2" />
<Image Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image3.jpg" ImageNumber = "3" />
<Image Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image4.jpg" ImageNumber = "4" />
<Image Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image5.jpg" ImageNumber = "5" />
</Instances>
Run Code Online (Sandbox Code Playgroud)
这些将导致C#Code for Parsing - 基于Jon Skeet的上述代码:
XElement root = XElement.Parse(text);
List<string> images = root.Elements("Image")
.Select(x => (string) x.Attribute("Location"))
.ToList();
Run Code Online (Sandbox Code Playgroud)
HTH :)
| 归档时间: |
|
| 查看次数: |
593 次 |
| 最近记录: |