簡體   English   中英

如何獲取xml中多個子節點的值?

[英]How to get the value for multiple subnode in xml?

  1. xml代碼:

      <Report> <ChartData> <ListName>area</ListName> <ViewName>Selecte List</ViewName> <YAxisFields> <YAxisField> <Name>Scheduled Start Date/Time</Name> <DataType>DateTime</DataType> <Category>Year</Category> </YAxisField> </YAxisFields> <XAxisFields> <XAxisField> <Name>Release Type</Name> <DataType>String</DataType> <Category> </Category> </XAxisField> </XAxisFields> </ChartConfig> </Report> 
  2. 通過使用以下代碼,我得到了子節點列表名和視圖名的值,

      XmlDocument doc = new XmlDocument(); doc.Load("XmlFileName"); XmlNodeList node = doc.SelectNodes("Report/ChartData"); foreach (XmlNode xn in node) { xn["ListName"].InnerXml = chartname; xn["ViewName"].InnerXml = SelectedList; **xn["YAxisFields/YAxisField"].InnerXml = yaxisfield; //not working, need to get the value for this xml node,need help in this line dono how to proceed** doc.Save("XmlFilename"); } 
  3. 首先,我嘗試使用這樣的代碼而不是上面的代碼,在此方法中,我需要創建多個對象以獲取每個節點的值,因此我嘗試通過為xmlnodelist創建對象來進行嘗試,然后使用foreach循環獲取每個節點的值但是在這種情況下,無法獲得YAxisFields / YAxisField的值,因為它還有父節點作為YAxisFields,子節點作為YAxisField,所以只有一種方法可以為xmlnode創建對象數目,或者還有其他方法可以這樣做嗎?

      XmlDocument doc = new XmlDocument(); doc.Load("XmlFileName"); XmlNode Listnode = doc.SelectSingleNode("Report/ChartData/ListName"); XmlNode Viewnode = doc.SelectSingleNode("Report/ChartData/ViewName"); if (Listnode != null) { Listnode.InnerXml = chartname; Viewnode.InnerXml = SelectedList; ; doc.Save("XmlFileName"); 

使用Linq來XML XDocument,如下所示:

doc.Root.Descendants("ChartData").ToList().ForEach(node =>
                {
                    node.Element("ListName").Value = chartname;
                    node.Element("ViewName").Value = SelectedList;
                });

暫無
暫無

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

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