2016-05-26 32 views
-1

我有下面的xml。如何读取XML节点值或名称c#

<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。有人能让我知道我在想什么吗?

回答

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. 
} 

看看你给XML包含一个字符串这Demo

+0

。但不是输入我给了xml路径。它给我错误在根目录下的数据是无效的。第1行,第1位。 – Farhan

+0

你的'xml'有问题,只是尝试用Internet Explorer或任何其他工具打开,你可以找出缺少的东西。 –

+0

<?XML版本= “1.0” 编码= “UTF-8”?> <日期时间日期= “2016年5月26日”> <时间时间= “上午09点53分46秒”>测试1 <日期时间日期= “2016年5月27日”> <时间时间= “上午09点54分56秒”> Test2的 Farhan