简体   繁体   English

C# 获取 XML 标记值

[英]C# GET XML TAG VALUE

I have an xml file named BackupManager.xml我有一个名为BackupManager.xml的 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”上得到空值

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;

}

Because you don't have an element with the ID "directory". 因为您没有ID为“directory”的元素。 Either you want 要么你想要

GetElementByID("backUpPath").GetAttribute("value");

Or 要么

GetElementsByTagName("directory");

Remember, that the second method returns a XMLNodeList! 请记住,第二种方法返回XMLNodeList!

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"];

            }
XmlDocument infodoc = new XmlDocument();
infodoc.Load("BackupManager.xml");
XmlElement directoryElement = document.GetElementById("directory");
string backupPath = directoryElement.GetAttribute("value");
if (xml.NodeType == XmlNodeType.Element && xml.Name == "Architecture")
{
    string architecture = xml.ReadElementContentAsString();
}

In past I had to deal with a huge XML and performance was as issue. 在过去,我不得不处理一个巨大的XML,性能也是问题所在。 All I needed was non-cached, forward-only, read-only access to 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 ?? "");
}
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);

            }

如果您想在这种情况下获取 'directory' 标记的值,请使用它作为简短的语法:

var directory = infodoc.GetElementsByTagName("directory")[0].Attributes["value"].Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM