How to append node and attribute to an existing Xm

2019-05-30 00:36发布

问题:

I have the following XML file. I have to add a node using XElement and XAttribute. How to do this?

   <?xml version="1.0" encoding="UTF-8"?>
    <Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner"> 
       <DataSets>
          <DataSet Name="Data">
              <Query>
                  <DataSourceName>DS1</DataSourceName>
                  <CommandText>SELECT FirstName,LastName FROM Person</CommandText>
              </Query>
</DataSet>
    <DataSet Name="table22">
      <Query>
        <DataSourceName>DS1</DataSourceName>
        <CommandText>New text2</CommandText>
      </Query>

How to add following XML text to above xml file at the end of both "/query" element using XElement And XAttribute

 <Fields>
        <Field Name="ReportId">
          <DataField>ReportId</DataField>
          <rd:TypeName>System.Int64</rd:TypeName>
        </Field> 

回答1:

You can try to select <Query> element first, then use AddAfterSelf() method to add <Fields> element after <Query> element, for example :

var doc = XElement.Parse(xml);
XNamespace ns = "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition";
var query = doc.Element(ns + "DataSets").Element(ns + "DataSet").Element(ns + "Query");

Console.WriteLine("before :");
Console.WriteLine(doc.ToString());
Console.WriteLine("");

XNamespace rd = "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner";
var field = new XElement(ns+"Fields",
                         new XElement(ns+"Field", new XAttribute("Name", "ReportId")
                                      , new XElement(ns+"DataField", "ReportId")
                                      , new XElement(rd + "TypeName", "System.Int64")));
query.AddAfterSelf(field);

Console.WriteLine("after :");
Console.WriteLine(doc.ToString());