如何读取XML节点值或命名c#

时间:2016-05-26 06:31:33

标签: c# xml

我的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。有人可以让我知道我错过了什么。

1 个答案:

答案 0 :(得分:2)

Xml中,没有名称为Value的属性,这可能是您收到空的原因。

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