C# 基础语法系列 —— 虽然没有什么难度,但确是我们日常工作中最常用的语法和业务需求。
C# XML 文件解析最简单的解决方案
下面我拿工作业务中常用的XML文件为例,写一个解析的Demo
<?xml version="1.0" encoding="utf-8"?>
<urlset content_method="full">
<url>
<lastmod>2018-03-07T07:52:39</lastmod>
<data>
<display>
<id>43241570</id>
<name>天狼说地产</name>
<headPortrait>
<contentUrl>url</contentUrl>
</headPortrait>
<level>资深房地产评论人</level>
<description>楼市分析,政策解读,三楼地产创始人,2017年企鹅号房产领域10强,为你置业保家护航</description>
<url>url</url>
<wapUrl>url</wapUrl>
<houseSpecialty>
<domain>重庆楼市分析 提供专业咨询</domain>
</houseSpecialty>
<followCount>1451</followCount>
<thumbupCount>1417</thumbupCount>
<rank>100</rank>
<status>1</status>
</display>
</data>
</url>
...
</urlset>
解析代码
/// <summary>
/// 解析输入(读取文件,并解析XML)
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private List<Display> ParseInput(string filePath)
{
List<Display> list = new List<Display>();
/
if (File.Exists(filePath))
{
//将文件内容转换成字符串
string readText = File.ReadAllText(filePath);
XElement root = XElement.Parse(readText);
//获取url 节点集合
if (root.Elements("url")?.Count() > 0)
{
//遍历 url 节点结合
foreach (var item in root.Elements("url"))
{
try
{
//解析 display节点, ?表示判空作用
var display = item.Element("data")?.Element("display");
if (display != null)
{
//解析所需要的数据
//** 注意 获取节点值的语法为 :display.Element("id").Value, 注意 ** Value属性**
list.Add(new Display()
{
UserId = SlConvert.TryToInt64(display.Element("id").Value),
Name = display.Element("name").Value,
Portrait = display.Element("headPortrait").Element("contentUrl").Value,
Level = display.Element("level").Value,
Description = display.Element("description").Value,
Domain = display.Element("houseSpecialty").Element("domain").Value,
AdministrativeAreaL2 = display.Element("houseSpecialty").Element("AdministrativeAreaL2").Value,
IsFree = SlConvert.TryToByte(display.Element("question").Element("isFree").Value),
Status = SlConvert.TryToByte(display.Element("status").Value),
ManageId = ParseManagerId(display.Element("wapUrl").Value)
});
}
}
catch (Exception ex)
{
continue;
}
}
}
}
return list;
}
喜欢,对您有帮助的话,就点个赞呗。 by yushuai_w。