簡體   English   中英

在c#中解析一個字符串

[英]Parsing a string in c#

假設有一個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>

此xml文件作為字符串讀取並傳遞給函數。 此xml文件包含有關特定圖像文件的信息。 我想從這個字符串中提取所有圖像文件的位置。 因此無論“位置”提交的價值如何,我都需要收集所有這些價值。 在C#中實現這一目標的最佳方法是什么?

謝謝,

最簡單的方法:將其解析為XML(我建議使用LINQ to XML),然后使用XML API添加信息。 將它作為原始字符數據自己處理是沒有意義的。

樣品:

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

(這將為任何不包含Location屬性的Bits元素賦予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>

這些將導致C#Code for Parsing - 基於Jon Skeet的上述代碼:

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

HTH :)

不使用字符串。 如果是XML,則按原樣讀取並使用XML LINQ庫進行查詢。

如果要解析XML,請使用框架中的XML類,尤其是XElement。

使用加載數據

XElement element = XElement.Parse(myString);

然后,您可以使用定義良好的API輕松操作對象。

我建議使用Linq to XML 使用簡單的Linq查詢,您可以獲得位置; 不解析必要的。

你可以使用Xpath表達式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM