[英]parsing an xml type string
我有這樣的字符串
<InitParams>
<myparams>
<Ad>true</Ad>
<Ay>true</Ay>
<Sd>false</Sd>
</myparams>
<myContent>
<Item>
<IM>true</IM>
<AL>1234</AL>
</Item>
</myContent>
</InitParams>
我需要標簽<IM>
和<AL>
之間的值。 剛接觸C#和.net時,不確定會是最好的方法。 在xmlDoc和linq上閱讀有關內容,但對於這種小的需求來說聽起來有些矯kill過正。
像LINQ to XML這樣的東西的全部要點是防止過度殺傷,因為它非常易於使用:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
namespace WhateverNamespaceYouWant
{
public class Item
{
public bool IM { get; set; }
public int AL { get; set; }
}
public class ItemsRepository
{
public IEnumerable<Item> GetAllItemsInXML()
{
var _items = new List<Item>();
var doc = XDocument.Load("this");
// finds every node of Item
doc.Descendants("Item").ToList()
.ForEach(item =>
{
var myItem = new Item() // your domain type
{
IM = item.Element("IM").Value.ConvertToValueType<bool>(),
AL = item.Element("AL").Value.ConvertToValueType<int>(),
};
_items.Add(myItem);
});
return _items;
}
}
public static class Extensions
{
public static T ConvertToValueType<T>(this string str) where T : struct
{
try
{
return (T)Convert.ChangeType(str, typeof(T));
}
catch
{
return default(T);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.