views:

46

answers:

1

I am using VS 2008. I have to create a wcf service and inside the service i have to do some basic operations on a xml file using LINQ to XML. I have to host the service in IIS 7.0 and consume it.

As part of the LINQ to XML I have to do the following tasks :

  1. find all the questions in all the Enquiry that answers are no
  2. modify the question and answer of Enquiry id="Enquiry2"

Pasted below is the XML file

<b:ServeySet xmlns:b="b:urn:schemas-microsoft-com">
  <b:Enquires>
    <b:Enquiry id="Enquiry1">
      <b:Question id="1" question="is the summer hot in LA?" answer="yes"/>
      <b:Question id="3" question="is this hard exercise?" answer="no"/>
      <b:Question id="2" question="is this awesome?" answer="yes"/>
    </b:Enquiry >
    <b:Enquiry id="Enquiry2">
      <b:Question id="1" question="what is SFO?" answer="City"/>
      <b:Question id="2" question="is this hard exercise?" answer="no"/>
    </b:Enquiry >
  </b:Enquires>
</b:ServeySet>
A: 

Try something like this:

static void Main(string[] args)
{
    // create the XDocument and load the file from disk
    XDocument doc = XDocument.Load("youroriginalfile.xml");

    // define the XML namespace used
    XNamespace b = "b:urn:schemas-microsoft-com:billing-data";

    // get all the questions where the answer is "no"
    var questionsWithAnswerNo = doc.Descendants(b + "Question").Where(x => x.Attribute("answer").Value == "no");

    // loop over these questions and do something.....
    foreach (XElement question in questionsWithAnswerNo)
    {
        // do something
    }

    // find questions for test with "test2" id
    var test2 = doc.Descendants(b + "Test").Where(x => x.Attribute("id").Value == "test2").FirstOrDefault();

    if(test2 != null)
    {
        // loop over questions, prepend a "TEST2: " to both question and
        // answer attribute of each of the questions
        foreach (XElement q2 in test2.Descendants(b + "Question"))
        {
            a2.Attribute("question").Value = "Test2: " + a2.Attribute("question").Value;
            a2.Attribute("answer").Value = "Test2: " + a2.Attribute("answer").Value;
        }

        // save the modified file
        doc.Save("newfile.xml");
    }
marc_s