簡體   English   中英

C# - 我可以通過搜索第二個屬性來 select XML 屬性的值嗎?

[英]C# - Can I select the value of an XML attribute by searching for a second attribute?

我想要 select “key”屬性匹配特定搜索的“data”屬性的值。

XML 文件將如下所示。

<connections>
  <production>
    <connection key="KEY1" data="value1" />
    <connection key="KEY2" data="value2" />
    <connection key="KEY3" data="value3" />
  </production>
</connections>

那么有沒有辦法通過搜索 key = key1 來返回數據屬性的值呢?

如果你想避免使用 XPath,你可以這樣做。

using System.Xml.Linq;

var xmlStr = File.ReadAllText("Testfile.xml");
XElement root = XElement.Parse(xmlStr);
var data = root.Element("production")
    .Elements().Where(x => x.Attribute("key").Value == "KEY1")
    .Select(x=>x.Attribute("data").Value)
    .First();
Console.WriteLine(data);

試試這個,使用 System.Xml 您可以讀取有問題的 xml 文件並遍歷節點以查找您的值。

private void YOUR_METHOD_NAME()
{
    // Call GetXml method which returns the result in the form of string
    string result = GetXml("xmlfile.xml", "KEY2");
    Debug.WriteLine(result);
}

private string GetXml(string filePath, string searchKey)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(filePath);

    XmlNodeList nodes = doc.SelectSingleNode("//connections/production").ChildNodes;

    string output = string.Empty;
    foreach (XmlNode node in nodes)
    {
        if (node.Attributes["key"].Value == searchKey)
        {
            output = node.Attributes["data"].Value;
        }
        else
        {
            continue;
        }
    }

    return output;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM