Process the XML response and convert to a collection that is not in the correct format

I need to process an XML response from a third-party REST API that I have no control over. The problem is the XML response in the wrong format, something like this:

<XML>
<Meta>
<Status>Success</Status>
<Debug/>
</Meta>
<Result>
<abc>
 <DivisionID>tttttttttt</DivisionID>
 <UserName><![CDATA[ xxx#xxxxx]]></UserName>
 <UserFirstName>xxxx</UserFirstName>
 <UserLastName>xxxx</UserLastName>
 <UserAccountType>xxxxxxx</UserAccountType>
 <UserEmail>xxxxx@xxxxx.xom</UserEmail>
 <UserAccountStatus>Active</UserAccountStatus>
</abc>
<def>
 <DivisionID/>
 <UserName><![CDATA[ xxx#xxxx]]></UserName>
 <UserFirstName>yyyy</UserFirstName>
 <UserLastName>vvvvvv</UserLastName>
 <UserAccountType>uuuuuuuuu</UserAccountType>
 <UserEmail>oooo@vvvvvv</UserEmail>
 <UserAccountStatus>Active</UserAccountStatus>
</def>
....contd
</Result>



       var requestUri = new Uri(uriString);
       HttpWebRequest httprequest =  (HttpWebRequest)WebRequest.Create(requestUri);
    var httpresponse = (HttpWebResponse)httprequest.GetResponse();
    Person people = new Person();
    List<Person> lstPerson = (from _person in         xmlDoc.Document.Element("Result").Elements("Result")
      select new Person
      {
      userName = Xdocument.Load(httpresponse.GetResponseStream()).Root.ToString(),
      userEmail = _person.Element("UserEmail").Value
      }).ToList();

I need to get a node with the values ​​"abc" and "def" and save them in UserName, which itself is the root node, and also to get the values ​​between them. therefore, how to do this, I tried different ways, but could not do it.

-1
source share
1 answer

Update

Person, userName UserEmail UserEmail, :

        try
        {
            // Load the XML from the external site
            XDocument xmlDoc;

            var requestUri = new Uri(uriString);
            HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(requestUri);

            using (var httpresponse = (HttpWebResponse)httprequest.GetResponse())
            using (var stream = httpresponse.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                xmlDoc = XDocument.Load(reader);
            }

            // Extract the name & email.
            var people = xmlDoc
                // Get the "Result" node
                .Root.Elements(xmlDoc.Root.Name.Namespace + "Result")
                // Loop through its elements
                .SelectMany(result => result.Elements())
                // Deserialize the element name and UserEmail sub-element value as a Person
                .Select(element => new Person { userName = element.Name.LocalName, userEmail = element.Element(xmlDoc.Root.Name.Namespace + "UserEmail").ValueSafe() })
                .ToList();

            // Process or return the list of people
        }
        catch (Exception ex)
        {
            // Handle any web exception encountered.
            Debug.WriteLine(ex);
            // Or rethrow if it can't be handled here
            throw;
        }

public static class XObjectExtensions
{
    public static string ValueSafe(this XElement element)
    {
        return element == null ? null : element.Value;
    }
}

.

XDocument XML, XmlSerializer , , ?

:

:.

    // Load the document
    var doc = XDocument.Parse(xml);

    var people = doc
        // Navigate to the list
        .Root.Elements("Result")
        .SelectMany(r => r.Elements())
        // Deserialize each element in the list as a KeyValuePair<string, Person>
        .Select(element =>
            {
                var name = element.Name;
                element.Name = typeof(Person).DefaultXmlElementName(); // Overwrite name with name used by serializer.
                using (var reader = element.CreateReader())
                {
                    var person = (Person)new XmlSerializer(typeof(Person)).Deserialize(reader);
                    return new KeyValuePair<string, Person>(name.LocalName, person);
                }
            })
        .ToList();

XML

    string xml = @"<XML>
        <Meta>
            <Status>Success</Status>
            <Debug/>
        </Meta>
        <Result>
            <abc>
                 <DivisionID>tttttttttt</DivisionID>
                 <UserName><![CDATA[ xxx#xxxxx]]></UserName>
                 <UserFirstName>xxxx</UserFirstName>
                 <UserLastName>xxxx</UserLastName>
                 <UserAccountType>xxxxxxx</UserAccountType>
                 <UserEmail>xxxxx@xxxxx.xom</UserEmail>
                 <UserAccountStatus>Active</UserAccountStatus>
            </abc>
            <def>
                 <DivisionID/>
                 <UserName><![CDATA[ xxx#xxxx]]></UserName>
                 <UserFirstName>yyyy</UserFirstName>
                 <UserLastName>vvvvvv</UserLastName>
                 <UserAccountType>uuuuuuuuu</UserAccountType>
                 <UserEmail>oooo@vvvvvv</UserEmail>
                 <UserAccountStatus>Active</UserAccountStatus>
            </def>
        </Result>
    </XML>
    ";

:

public static class XmlSerializationHelper
{
    public static string DefaultXmlElementName(this Type type)
    {
        var xmlType = type.GetCustomAttribute<XmlTypeAttribute>();
        if (xmlType != null && !string.IsNullOrEmpty(xmlType.TypeName))
            return xmlType.TypeName;
        var xmlRoot = type.GetCustomAttribute<XmlRootAttribute>();
        if (xmlRoot != null && !string.IsNullOrEmpty(xmlRoot.ElementName))
            return xmlRoot.ElementName;
        return type.Name;
    }
}
0

Source: https://habr.com/ru/post/1621956/


All Articles