0

I need to consume web service in C# website application. I generated the proxy class using wsdl command and I am able to use it to invoke the webservice and get the result.

The issue is that I have 2 fields in response xml which provide data in cdata tags. The values for these 2 fields are returned as empty strings. I tried to add the XMLText attribute to the field definition in the proxy as shown below.

   [XmlText]       
   public string Title {
        get {
            return this.TitleField;
        }
        set {
            this.TitleField = value;
        }
    }

    [XmlText]
    public string Description {
        get {
            return this.descriptionField;
        }
        set {
            this.descriptionField = value;
        }
    }

but I am getting the following error when the above code change is done:

Exception Details: System.InvalidOperationException: Cannot serialize object of type 'WService.XXXXXXXXXX' because it has multiple XmlText attributes. Consider using an array of strings with XmlTextAttribute for serialization of a mixed complex type.

Here is how the values appear in the response: <Title><![CDATA[test title]]></Title> <Description><![CDATA[test description ]]></Description>

The datatype for both these elements is specified as string in the XSD. Please let me know how this issue needs to be fixed.

Bhuvana
  • 152
  • 1
  • 7
  • To summarize the issue: I would like to read the value of the XML element which has CDATA in it. How should the C# proxy class be modified to achieve this. – Bhuvana Dec 07 '12 at 09:00

1 Answers1

0

From How do you serialize a string as CDATA using XmlSerializer?

[Serializable]
public class MyClass
{
    public MyClass() { }

    [XmlIgnore]
    public string MyString { get; set; }
    [XmlElement("MyString")]
    public System.Xml.XmlCDataSection MyStringCDATA
    {
        get
        {
            return new System.Xml.XmlDocument().CreateCDataSection(MyString);
        }
        set
        {
            MyString = value.Value;
        }
    }
}

Usage:

MyClass mc = new MyClass();
mc.MyString = "<test>Hello World</test>";
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
StringWriter writer = new StringWriter();
serializer.Serialize(writer, mc);
Console.WriteLine(writer.ToString());

Output:

<?xml version="1.0" encoding="utf-16"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <MyString><![CDATA[<test>Hello World</test>]]></MyString>
</MyClass>
Community
  • 1
  • 1
Jeroen K
  • 10,258
  • 5
  • 41
  • 40