如何在xml中获取多个子节点的值?

时间:2013-01-23 07:33:50

标签: c# asp.net

  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. 我通过使用获得了子节点listname和viewname的值                 在代码下面,

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

1 个答案:

答案 0 :(得分:1)

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

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