Development Tip

XML을 동적 C # 객체로 변환

yourdevel 2020. 12. 30. 19:43
반응형

XML을 동적 C # 객체로 변환


다음 C # 코드를 사용하여 JSON.Net 프레임 워크를 사용하여 JSON 데이터 문자열을 동적 개체로 변환했습니다.

// Creates a dynamic .Net object representing the JSON data
var ProductDB = JsonConvert.DeserializeObject<dynamic>(JsonData);

일단 변환되면 다음과 같은 코드를 사용하여 요소에 직접 액세스 할 수 있습니다.

// Variables to be used
string ProductID;
string ProductType;
int ProductQty;

// Loop through each of the products
foreach (dynamic product in ProductDB.products)
{
    ProductID = product.id;
    ProductType = product.type;
    ProductQty = product.qty;
}

XML 데이터 작업에 이와 유사한 것이 있습니까? JSON.net을 사용하여 XML을 JSON으로 변환 한 다음 위의 코드를 재사용 할 수 있지만 속임수처럼 느껴집니다.

감사.


XDocument doc = XDocument.Parse(xmlData); //or XDocument.Load(path)
string jsonText = JsonConvert.SerializeXNode(doc);
dynamic dyn = JsonConvert.DeserializeObject<ExpandoObject>(jsonText);

"속임수"가 답이라고 생각합니다. xml 솔루션은 매우 깁니다. :)


미래의 방문자를위한 대안 인 ITDevSpace의 하나는 자식이있는 요소에 대한 속성을 포함하지 않습니다.

public class XmlWrapper
{
    public static dynamic Convert(XElement parent)
    {
        dynamic output = new ExpandoObject();

        output.Name = parent.Name.LocalName;
        output.Value = parent.Value;

        output.HasAttributes = parent.HasAttributes;
        if (parent.HasAttributes)
        {
            output.Attributes = new List<KeyValuePair<string, string>>();
            foreach (XAttribute attr in parent.Attributes())
            {
                KeyValuePair<string, string> temp = new KeyValuePair<string, string>(attr.Name.LocalName, attr.Value);
                output.Attributes.Add(temp);
            }
        }

        output.HasElements = parent.HasElements;
        if (parent.HasElements)
        {
            output.Elements = new List<dynamic>();
            foreach (XElement element in parent.Elements())
            {
                dynamic temp = Convert(element);
                output.Elements.Add(temp);
            }
        }

        return output;
    }
}

@FSX의 답변에서 " Parse XML to dynamic object in C # " 의 솔루션을 성공적으로 사용했습니다 .

public class XmlToDynamic
{
    public static void Parse(dynamic parent, XElement node)
    {
        if (node.HasElements)
        {
            if (node.Elements(node.Elements().First().Name.LocalName).Count() > 1)
            {
                //list
                var item = new ExpandoObject();
                var list = new List<dynamic>();
                foreach (var element in node.Elements())
                {                        
                    Parse(list, element);                        
                }

                AddProperty(item, node.Elements().First().Name.LocalName, list);
                AddProperty(parent, node.Name.ToString(), item);
            }
            else
            {
                var item = new ExpandoObject();

                foreach (var attribute in node.Attributes())
                {
                    AddProperty(item, attribute.Name.ToString(), attribute.Value.Trim());
                }

                //element
                foreach (var element in node.Elements())
                {
                    Parse(item, element);
                }

                AddProperty(parent, node.Name.ToString(), item);
            }
        }
        else
        {
            AddProperty(parent, node.Name.ToString(), node.Value.Trim());
        }
    }

    private static void AddProperty(dynamic parent, string name, object value)
    {
        if (parent is List<dynamic>)
        {
            (parent as List<dynamic>).Add(value);
        }
        else
        {
            (parent as IDictionary<String, object>)[name] = value;
        }
    }
}

Cinchoo ETL -xml을 동적 객체로 파싱 할 수있는 오픈 소스 라이브러리

using (var p = ChoXmlReader.LoadText(xml).WithXPath("/"))
{
    foreach (dynamic rec in p)
        Console.WriteLine(rec.Dump());
}

Checkout CodeProject article for some additional help.

Disclaimer: I'm the author of this library.

ReferenceURL : https://stackoverflow.com/questions/13171525/converting-xml-to-a-dynamic-c-sharp-object

반응형