dimanche 28 juin 2015

C# wrap multiple elements in one element in XML

How do I wrap multiple elements within an element in an XML file?

I have code that creates an XDocument like so:

 doc = new XDocument(
                  new System.Xml.Linq.XDeclaration("1.0", "UTF-8", string.Empty),
                  new XElement("JobSvc",
                      new XAttribute("environment", this.environment),
                      new XAttribute("dateTo", DateTime.Today.ToShortDateString()),
                      new XAttribute("dateFrom", DateTime.Today.AddDays(-7).ToShortDateString())
              ));
            return doc;

and then I have code that adds elements to this document, such as:

  public void Append_ProcessName_Server_Type(XDocument doc)
        {//i will replace confidential info
            var name_Type_Server =   new XElement("Wrapper",
                                                    new XAttribute("x","******"),
                                                    new XAttribute("x","x"),
                                                    new XAttribute("x","x"));
            doc.Root.Add(name_Type_Server);
        }

then I add more elements under the element created above with this:

 public void AppendExtractedRowsAsElements(XDocument doc)
        {
            var newElement = new XElement("processId", this.id,
                    new XAttribute("duration", this.duration),
                    new XAttribute("eventTime", this.eventTime),
                    new XAttribute("source", this.source),
                    new XAttribute("runNumber", run));
            doc.Root.Add(newElement);

        }

this works fine and produces an output like this:

<?xml version="1.0" encoding="utf-8"?>
<JobSvc dateAndTimeExecuted="2015-06-29T14:38:48.588082+08:00" environment="" dateFrom="6/22/2015" dateTo="6/29/2015">
  <process server="xxx" type="x" name="x" />
  <processId duration="12182" eventTime="6/5/2015 6:23:02 AM" source="***" runNumber="1">xxxxxx</processId>
  <processId duration="6574" eventTime="6/12/2015 4:47:36 AM" source="***" runNumber="2">xxxxxx</processId>

how do I make it output like this: where all the processid elements are wrapped by the process element?

<?xml version="1.0" encoding="utf-8"?>
    <JobSvc dateAndTimeExecuted="2015-06-29T14:38:48.588082+08:00" environment="" dateFrom="6/22/2015" dateTo="6/29/2015">
      <process server="xxx" type="x" name="x" >
      <processId duration="12182" eventTime="6/5/2015 6:23:02 AM" source="***" runNumber="1">xxxxxx</processId>
      <processId duration="6574" eventTime="6/12/2015 4:47:36 AM" source="***" runNumber="2">xxxxxx</processId>
</process>

Aucun commentaire:

Enregistrer un commentaire