-2

I have this XML file which I am having troubles deserializing it, so I'm going kind of way around it. I have an XML string and I want to get a value out of it. Let's say this is my XML string:

string XMLstring = "<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<InputText>123</InputText>
<InputText>Apple</InputText>
<InputText>John</InputText>
</note>";

Now, I have tried something like checking if the XMLstring contains InputText, but I want someway to get all the three values from there and then use them somewhere. Is there any way I can do this without having to deserialize it?

Trevor
  • 7,777
  • 6
  • 31
  • 50
  • 1
    "without having to deserialize it" I don't see how that's possible. If you want to find the elements you're interested in, and obtain the contents of said elements, you need to parse the XML. – gunr2171 Mar 02 '22 at 16:11
  • We won't know how to make the changes to your existing code base without seeing your original code. Please post a [mre], and fully explain what needs to be modified. – gunr2171 Mar 02 '22 at 16:11
  • 1
    Does this answer your question? [Read a XML (from a string) and get some fields - Problems reading XML](https://stackoverflow.com/questions/8401280/read-a-xml-from-a-string-and-get-some-fields-problems-reading-xml). How are you reading this file, if you are, I just see a hard coded string? – Trevor Mar 02 '22 at 16:12
  • Another thing you could do is convert your XML String to JSON and then proceed. – D idsea J Mar 02 '22 at 16:12
  • Pretty easy: https://dotnetfiddle.net/sIUuV2 – Fildor Mar 02 '22 at 16:15
  • 1
    @Fildor Might want to double check that link – John Wu Mar 02 '22 at 16:17

1 Answers1

1

You can use LINQ-to-XML to parse the string and obtain the values.

using System.Linq;
using System.Xml.Linq;

public static void Main()
{
    var xml = @"<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body><InputText>123</InputText><InputText>Apple</InputText><InputText>John</InputText></note>";
        
    var list = XDocument.Parse(xml).Descendants("InputText").Select( x => x.Value );
    foreach (var item in list) Console.WriteLine(item);
}

Output:

123
Apple
John

Fiddle

John Wu
  • 50,556
  • 8
  • 44
  • 80