2016-05-26 19 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> 

iは、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ループ内に「2016年5月26日」/ 2016年5月27日であるべきです。何人かが私に何が欠けているか教えてもらえますか?

答えて

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"); 
     } 

あなたはすべての要素のためにそれをしたい場合は、XML文字列として含まれている与えているこのDemo

+0

を見てみましょうWhere

var matches = doc.Root.Elements("DateTime") .Where(x=>x.Attribute("date").Value == attribute2.Value); foreach(var match in matches) { // logic here. } 

を使用しています。代わりに入力私はXMLパスを与えている。それは私にエラーを与えているルートレベルのデータが無効です。 1行目、1位。 – Farhan

+0

'xml'に何か問題があります。インターネットエクスプローラや他のツールで開くと、見つからないものを見つけ出すことができます。 –

+0

の<?xml version = "1.0" エンコード= "UTF-8"?> <時間時間= "午前9時53分46秒AM"> <= "2016年5月26日" のDateTime日付> Test1を <時間時間= "9時54分56秒AM"> <= "2016年5月27日" のDateTime日付> Farhan

関連する問題