C# 获取 XML 标记值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13605396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# GET XML TAG VALUE
提问by Rakesh
I have an xml file named BackupManager.xml
我有一个名为的 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>
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'
我正在尝试从标签中获取值到字符串 例如:- 我需要将 'backUpPath' 标签的值作为 'D:/BACKUPS/' 到一个字符串说 'str'
The code I have tried is
我试过的代码是
XmlDocument infodoc = new XmlDocument();
infodoc.Load("BackupManager.xml");
//int col = infodoc.GetElementsByTagName("directory").Count;
String str = infodoc.GetElementByID("directory").value;
But i am getting null value on 'str'
但我在“str”上得到空值
采纳答案by Pranay Rana
try out
试用
linq to xml way
linq 到 xml 的方式
IEnumerable<XElement> direclty = infodoc.Elements("Settings").Elements("directory");
var rosterUserIds = direclty .Select(r => r.Attribute("value").Value);
OR
或者
XmlNodeList nodeList=
(infodoc.SelectNodes("configuration/Settings/directory"));
foreach (XmlNode elem in nodeList)
{
string strValue = elem.Attributes[1].Value;
}
回答by looper
Because you don't have an element with the ID "directory". Either you want
因为您没有 ID 为“目录”的元素。无论你想要
GetElementByID("backUpPath").GetAttribute("value");
Or
或者
GetElementsByTagName("directory");
Remember, that the second method returns a XMLNodeList!
请记住,第二个方法返回一个 XMLNodeList!
回答by S3ddi9
if you want u can use XmlReader
如果你愿意,你可以使用 XmlReader
string str ="";
using (var reader = new StreamReader(BackupManager.xml))
{
var all = reader.ReadToEnd();
StringReader stringReader = new StringReader(all);
XmlReader xmlReader = XmlTextReader.Create(stringReader,new System.Xml.XmlReaderSettings() { IgnoreWhitespace = true, IgnoreComments = true });
while (xmlReader.Read())
if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "directory")
str = xmlReader["value"];
}
回答by Black Stallion
XmlDocument infodoc = new XmlDocument();
infodoc.Load("BackupManager.xml");
XmlElement directoryElement = document.GetElementById("directory");
string backupPath = directoryElement.GetAttribute("value");
回答by Elephant
if (xml.NodeType == XmlNodeType.Element && xml.Name == "Architecture")
{
string architecture = xml.ReadElementContentAsString();
}
回答by ablaze
In past I had to deal with a huge XML and performance was as issue. All I needed was non-cached, forward-only, read-only access to XML.
过去我不得不处理一个巨大的 XML 并且性能是一个问题。我所需要的只是对 XML 的非缓存、只进、只读访问。
Additionally, I did not have had the control over the schema, just had to squeeze out certain tag values, from XML and also CDATA.
此外,我无法控制模式,只需要从 XML 和CDATA 中挤出某些标签值。
Below is what I ended up using :
以下是我最终使用的内容:
private string GetValueFromXmlTag(string xml, string tag)
{
if (xml == null || tag == null || xml.Length == 0 || tag.Length == 0)
return "";
string
startTag = "<" + tag + ">",
endTag = "</" + tag + ">",
value = null;
int
startTagIndex = xml.IndexOf(tag, StringComparison.OrdinalIgnoreCase),
endTagIndex = xml.IndexOf(endTag, StringComparison.OrdinalIgnoreCase);
if (startTagIndex < 0 || endTagIndex < 0)
return "";
int valueIndex = startTagIndex += startTag.Length - 1;
try
{
value = xml.Substring(valueIndex, endTagIndex - valueIndex);
}
catch (ArgumentOutOfRangeException responseXmlParserEx)
{
string err = string.Format("Error reading value for \"{0}\" tag from XXX XML", tag);
log.Error(err, responseXmlParserEx);
}
return (value ?? "");
}
回答by Shubham Koolwal
XmlDocument infodoc = new XmlDocument();
//Server.MapPath() return the xml file address
infodoc.Load(Server.MapPath("~/XMLFile1.xml"));
XmlNodeList nodeList =
(infodoc.SelectNodes("configuration/Settings/backUPpath"));
foreach (XmlNode elem in nodeList)
{
Response.Write(elem.Attributes[1].Value);
}

