1

My xml looks like this:

<document>
    <body>
        <p>
            <text>asdasdasdasd</text>
        </p>
        <text>  </text>
        <p>
            <text>Bl abloa blasdasdasd</text>
        </p>
    </body>     
</document>

So what i want to do is to parse body element as string.

    [XmlRoot(ElementName = "document")]
    public class Document
    {      
        [XmlElement(ElementName = "body")]
        public string Body { get; set; }   
    }   

I've tried [XmlText] and different attributes on like this [XmlText(Type = typeof(string))]

I'm trying to do this directly as a parameter in my controller method:

    [AllowAnonymous]
    [HttpPost]
    [Route("")]
    public async Task SearchResult([FromBody] SearchResultDataContract searchResult)
    {
        try

Were SearchResultDataContract is the document object.

But I haven't managed to find any solutions.

2
  • you want whole <body>....</body> node as string or only want <text> node inside? Commented Feb 5, 2019 at 13:55
  • Easiest would have been the whole body node as a string :) @er-mfahhgk Commented Feb 5, 2019 at 13:56

2 Answers 2

2
[XmlRoot(ElementName = "document")]
public class Document
{
    [XmlElement("body")]
    public XmlElement Body { get; set; }
}

should work, as long as we're talking about xhtml, not html. You can't deal with string directly, AFAIK - the encoder won't trust you that your xml will always be well-formed - but it trusts XmlElement. You could always add something that shims between the two, if needed.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! I've been trying to do this for hours! Great solution, from xmlelement i can just grab the innerXml to get it as a string. Thanks :)
Hmm it seems that outerXml only gives me the first node "<p>" and not the other nodes inside of body... Do you know why?
@DanielGustafsson oh eesh, that's vexing; but I guess it makes sense... I ... don't have good solutions in that case; I'll delete this answer
ooh no :( Thanks anyway!
0

I managed to solve this by creating my own extension for the deserialization using this: Deserialize element value as string although it contains mixed content

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.