簡體   English   中英

如何讀取XML節點值或名稱C#

[英]how to read XML node value or name c#

我有下面的XML。

<Data>
  <DateTime date="05-26-2016">
   <Time time="09:53:46 AM">Test1</Time>
</DateTime>
<DateTime date="05-27-2016">
<Time time="09:54:56 AM">Test2</Time>
</DateTime>
</Data>

我使用下面的代碼來獲取DateTime名稱/值,但它給出了null。

xmlDoc.Load(@"E:\testdoc.xml");
XmlElement rootNode = xmlDoc.DocumentElement;
foreach (XmlElement a in rootNode.ChildNodes)
        {
            var attributeValue = a.GetAttribute("Value");
            if (a.Attributes["Value"].Value == attribute2.Value)
            {
                a.AppendChild(userChildNode2);
            }
        }

在foreach循環中,“ attributeValue”的必需輸出應為“ 05-26-2016” / 05-27-2016。 有人可以讓我知道我在想什么嗎?

在您的Xml ,沒有名稱為Value屬性,這可能是您收到null的原因。

a.GetAttribute("Value"); // Will return null. 

我建議您可以使用XDocument並執行此操作。

XDocument doc = XDocument.Load(filename);       
var fmatch = doc.Root.Elements("DateTime")
                      .FirstOrDefault(x=>x.Attribute("date").Value == attribute2.Value);

if(fmatch!= null)
{
    fmatch.Add(new XElement("child", "value")); // use details you would like to add as an element. 
}

// add attribute in element use below

        if (fmatch != null)
        {
            fmatch.Add( new XElement("Time", new XAttribute("time", DateTime.Now.ToString("hh:mm:ss tt")),"Test append in same date"));  
            doc.Save(@"E:\testdoc.xml");
        }

如果要對所有元素執行此操作,請使用Where子句

var matches = doc.Root.Elements("DateTime")
                      .Where(x=>x.Attribute("date").Value == attribute2.Value);

foreach(var match in matches)
{
    // logic here.
}

看看這個Demo

暫無
暫無

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

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