簡體   English   中英

C# 獲取 XML 標記值

[英]C# GET XML TAG VALUE

我有一個名為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>

我正在嘗試從標簽中獲取值到字符串 例如:- 我需要將 'backUpPath' 標簽的值作為 'D:/BACKUPS/' 到一個字符串說 'str'

我試過的代碼是

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

但我在“str”上得到空值

試用

linq到xml的方式

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;

}

因為您沒有ID為“directory”的元素。 要么你想要

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

要么

GetElementsByTagName("directory");

請記住,第二種方法返回XMLNodeList!

如果你想要你可以使用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();
}

在過去,我不得不處理一個巨大的XML,性能也是問題所在。 我所需要的只是對XML的非緩存,僅向前,只讀訪問。

另外,我沒有控制架構,只需要從XML和CDATA中擠出某些標簽值。

以下是我最終使用的內容:

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