2015-07-11 78 views
1

我一直在努力,在過去的一天閱讀和修改這個XML修訂XML文件

<TimeSeriesDocument xmlns:xsd="http://www.w3.org/2001/XMLSchema"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:Test"> 
<DocumentIdentification v="ZDAE_02417b6a-477a-a-4aa19e1c4712"/> 
<TimeSeries> 
<Period> 
    <TimeInterval v="12" /> 
    <Resolution v="PT1H" /> 
    <Interval> 
    <Pos v="17" /> 
    <Qty v="0" /> 
    </Interval> 
    <Interval> 
    <Pos v="19" /> 
    <Qty v="10" /> 
    </Interval> 
</Period> 
</TimeSeries> 
</TimeSeriesDocument> 

我想期內的每個區間內修改每個數量

我一直用後裔,但我努力循環每個間隔,並挑選和更改數量

var doc = XDocument.Load(test.xml); 
var periods = doc.Descendants("TimeSeriesDocument/TimeSeries").Select(e => new { name = e.Element("Period").Value }); 

你能幫忙嗎?

+0

你想用它來讀取XML文件是什麼類型的項目? –

回答

1

通過節點數量的樣本控制檯應用程序循環,並設置新的值當V屬性:

class Program 
{ 
    static void Main(string[] args) 
    { 
     var document = new XmlDocument(); 
     document.Load("Sample.xml"); 

     XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable); 
     nsmgr.AddNamespace("ns", "urn:Test"); 

     var intervalNodes = document.SelectNodes("//ns:Interval", nsmgr); 
     foreach(XmlNode node in intervalNodes) 
     { 
      var quantityNode = node.SelectSingleNode("./ns:Qty", nsmgr); 
      quantityNode.Attributes["v"].Value = "New Value"; 
     } 
    } 
} 
+0

優秀謝謝 –

1
XNamespace ns = "urn:Test"; 

XElement doc = XElement.Load("file.xml"); 

var periods = doc.Descendants(ns + "Period"); 
var intervals = periods.Elements(ns + "Interval"); 

foreach (var qty in intervals.Elements(ns + "Qty")) 
{ 
    qty.Attribute("v").Value = "42"; 
} 
+0

優秀謝謝 –