C# 获取 XML 标记值 [英] C# GET XML TAG VALUE

查看:31
本文介绍了C# 获取 XML 标记值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 BackupManager.xml

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<Settings>
<directory id="backUpPath" value="D:/BACKUPS/"></directory>
<filename id="feilname" value="SameName"></filename>
<period id ="period" value="15"></period>
</Settings>
</configuration>

我正在尝试从标签中获取值到字符串例如:- 我需要将 'backUpPath' 标记的值设为 'D:/BACKUPS/' 到一个字符串,例如 'str'

I am trying to get value from the tags to a string Eg:- I need value of 'backUpPath' tag as 'D:/BACKUPS/' to a string say 'str'

我试过的代码是

XmlDocument infodoc = new XmlDocument();
infodoc.Load("BackupManager.xml");
//int col = infodoc.GetElementsByTagName("directory").Count;
String str = infodoc.GetElementByID("directory").value;

但是我在'str'上得到空值

But i am getting null value on 'str'

推荐答案

试用

linq 到 xml 的方式

linq to xml way

IEnumerable<XElement> direclty = infodoc.Elements("Settings").Elements("directory");
var rosterUserIds = direclty .Select(r => r.Attribute("value").Value);

   XmlNodeList nodeList=
(infodoc.SelectNodes("configuration/Settings/directory"));

foreach (XmlNode elem in nodeList)
{
string strValue = elem.Attributes[1].Value;

}

这篇关于C# 获取 XML 标记值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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