在C#中解析字符串 [英] Parsing a string in c#

查看:109
本文介绍了在C#中解析字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个如下所示的xml文件:

Suppose there is an xml file like below:

<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>

此xml文件将作为字符串读取,并传递给函数.此xml文件包含有关特定图像文件的信息.我想从该字符串中提取所有图像文件的位置.因此,无论位置"价值是什么,我都需要收集所有这些价值.在C#中实现此目标的最佳方法是什么.

This xml file is read as a string and passed on to a function. This xml file has information about a particular image file. I want to extract the location of all the image files from this string. So whatever is value of "location" filed i need to collect all those value. What is the best way to achieve this in C#.

谢谢

推荐答案

请注意,这里的结构不是XElement.Parse的有效XML,因为您的元素没有名称,而只有属性.

Take care, your structure here is not a valid XML for the XElement.Parse because your elements do not have a name, but only attributes.

可能的正确结构是:

<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>

这些将导致遵循以下C#代码进行解析-基于上面的Jon Skeet的代码:

These would result in folowing C# Code for Parsing - based on Jon Skeet's code from above:

 XElement root = XElement.Parse(text);
 List<string> images = root.Elements("Image")
                           .Select(x => (string) x.Attribute("Location"))
                           .ToList();

HTH:)

这篇关于在C#中解析字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆