2017-03-20 1 views
1

컨트롤러 중 하나에서 XML 페이로드를 deserialise하려고하는 성가신 문제가 발생했지만 페이로드에는 네임 스페이스가 없거나 모든 요소에 네임 스페이스 접두사가있을 수 있습니다.ASP.NET WebAPI에서 요소 접두어로 XML을 역 직렬화하는 방법은 무엇입니까?

Namespace = ""으로 모델에 XML 특성을 추가하려고 시도했지만 모델을 신경 쓰지 않으려 고 시도했지만 작동하지 않았습니다. 또한 XmlSerialiser에 기본 네임 스페이스를 ""으로 설정하려고 시도했지만 도움이되지 않았습니다. 또한 [XmlNamespaceDeclarations] 속성을 시도했지만 운이 없었습니다.

다음은 설명에서 명확하지 않은 경우를 대비하여받을 수있는 두 가지 페이로드의 예입니다. 아래

<root> <element>Example</element> <secondElement>Example</secondElement> </root>

그리고

<ex:root namespace:ex="http://example.com/ns"> <ex:element>Example</ex:element> <ex:secondElement>Example2</ex:secondElement> </ex:root>

내가 진심이 다른 곳에서 대답 한 경우 사과

[XmlRoot("root")] 
public class Root 
{ 
    [XmlElement("element")] 
    public string Element {get; set;} 

    [XmlElement("secondElement")] 
    public string SecondElement {get; set;} 
} 

에 deserialise을 시도 할 것이라고 페이로드에 대한 모델이다하지만 난이 내 문제와 관련이있는 모든 질문에 해결책을 시도했지만 성공하지 못했습니다.

미리 감사드립니다.

편집 : 고정 네임 스페이스 XML 예제

답변

1

회원님이 역 직렬화하려고 노력하지만, 이런 일이 어떻게 작동하는지 확인하십시오

var xml = File.ReadAllText("sample.xml"); 
var serializer = new XmlSerializer(typeof(Root)); 
var obj = serializer.Deserialize(new StringReader(xml)); 
0

을 내부에 먼저 표시 할 수 있습니다 두 개의 서로 다른 가능한 요소가 있기 때문에 루트, 우리는 그 선택을 표현할 필요가있다. 나는 올바른 코드를 직접 쓰려고했지만 실패했다. 그래서 대신 먼저 원하는 것을 표현하기 위해 스키마를 작성한 다음 xsd command line tool을 사용하여 C# 코드 을 생성했다.

첫째, 주요 스키마 :

<?xml version="1.0" encoding="utf-8"?> 
<xs:schema xmlns:ex="http://example.com/ns" attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:import namespace="http://example.com/ns" /> 
    <xs:element name="root"> 
     <xs:complexType> 
      <xs:sequence> 
       <xs:choice> 
        <xs:element ref="ex:element" /> 
        <xs:element name="element" > 
        </xs:element> 
       </xs:choice> 
       <xs:choice> 
        <xs:element ref="ex:secondElement" /> 
        <xs:element name="secondElement" /> 
       </xs:choice> 
      </xs:sequence> 
     </xs:complexType> 
    </xs:element> 
</xs:schema> 

그리고 우리는 ns 스키마를 설명하는 다른 스키마가 필요합니다

<?xml version="1.0" encoding="utf-8"?> 
<xs:schema id="XMLSchema1" 
    targetNamespace="http://example.com/ns" 
    elementFormDefault="qualified" 
    xmlns="http://example.com/ns" 
    xmlns:mstns="http://example.com/ns" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
> 
    <xs:element name="element"/> 
    <xs:element name="secondElement"/> 
</xs:schema> 

을 그리고 우리가 xsd /classes XmlFile1.xsd XMLSchema1.xsd를 실행은 (가정 즉, 두 주어진 이름이다 xsd 파일

이것은 클래스를 내뱉습니다 :

//------------------------------------------------------------------------------ 
// <auto-generated> 
//  This code was generated by a tool. 
//  Runtime Version:4.0.30319.42000 
// 
//  Changes to this file may cause incorrect behavior and will be lost if 
//  the code is regenerated. 
// </auto-generated> 
//------------------------------------------------------------------------------ 

using System.Xml.Serialization; 

// 
// This source code was auto-generated by xsd, Version=4.6.1055.0. 
// 


/// <remarks/> 
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")] 
[System.SerializableAttribute()] 
[System.Diagnostics.DebuggerStepThroughAttribute()] 
[System.ComponentModel.DesignerCategoryAttribute("code")] 
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] 
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)] 
public partial class root { 

    private object itemField; 

    private ItemChoiceType itemElementNameField; 

    private object item1Field; 

    private Item1ChoiceType item1ElementNameField; 

    /// <remarks/> 
    [System.Xml.Serialization.XmlElementAttribute("element", typeof(object))] 
    [System.Xml.Serialization.XmlElementAttribute("element", typeof(object), Namespace="http://example.com/ns")] 
    [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")] 
    public object Item { 
     get { 
      return this.itemField; 
     } 
     set { 
      this.itemField = value; 
     } 
    } 

    /// <remarks/> 
    [System.Xml.Serialization.XmlIgnoreAttribute()] 
    public ItemChoiceType ItemElementName { 
     get { 
      return this.itemElementNameField; 
     } 
     set { 
      this.itemElementNameField = value; 
     } 
    } 

    /// <remarks/> 
    [System.Xml.Serialization.XmlElementAttribute("secondElement", typeof(object), Namespace="http://example.com/ns")] 
    [System.Xml.Serialization.XmlElementAttribute("secondElement", typeof(object))] 
    [System.Xml.Serialization.XmlChoiceIdentifierAttribute("Item1ElementName")] 
    public object Item1 { 
     get { 
      return this.item1Field; 
     } 
     set { 
      this.item1Field = value; 
     } 
    } 

    /// <remarks/> 
    [System.Xml.Serialization.XmlIgnoreAttribute()] 
    public Item1ChoiceType Item1ElementName { 
     get { 
      return this.item1ElementNameField; 
     } 
     set { 
      this.item1ElementNameField = value; 
     } 
    } 
} 

/// <remarks/> 
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")] 
[System.SerializableAttribute()] 
[System.Xml.Serialization.XmlTypeAttribute(IncludeInSchema=false)] 
public enum ItemChoiceType { 

    /// <remarks/> 
    element, 

    /// <remarks/> 
    [System.Xml.Serialization.XmlEnumAttribute("http://example.com/ns:element")] 
    element1, 
} 

/// <remarks/> 
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")] 
[System.SerializableAttribute()] 
[System.Xml.Serialization.XmlTypeAttribute(IncludeInSchema=false)] 
public enum Item1ChoiceType { 

    /// <remarks/> 
    [System.Xml.Serialization.XmlEnumAttribute("http://example.com/ns:secondElement")] 
    secondElement, 

    /// <remarks/> 
    [System.Xml.Serialization.XmlEnumAttribute("secondElement")] 
    secondElement1, 
} 

정확한 요구에 맞게 편집/조정할 수 있습니다. 예 : 여기에 사용 된 형식 (object)이 이상적이라고 생각하지 않으며 아마도 string으로 조정할 수 있습니다.

using System.Xml.Serialization; 

[System.Serializable()] 
[XmlType(AnonymousType = true)] 
[XmlRoot("root", Namespace = "", IsNullable = false)] 
public partial class Root 
{ 

    [XmlElement("element", typeof(string))] 
    [XmlElement("element", typeof(string), Namespace = "http://example.com/ns")] 
    [XmlChoiceIdentifier("ElementType")] 
    public string Element { get; set; } 

    [XmlIgnore()] 
    public ElementType ElementType { get; set; } 

    [XmlElement("secondElement", typeof(string), Namespace = "http://example.com/ns")] 
    [XmlElement("secondElement", typeof(string))] 
    [XmlChoiceIdentifier("SecondElementType")] 
    public string SecondElement { get; set; } 

    [XmlIgnore()] 
    public SecondElementType SecondElementType { get; set; } 
} 

/// <remarks/> 
[System.Serializable()] 
[XmlType(IncludeInSchema = false)] 
public enum ElementType 
{ 
    element, 
    [XmlEnum("http://example.com/ns:element")] 
    nsElement, 
} 

/// <remarks/> 
[System.Serializable()] 
[XmlType(IncludeInSchema = false)] 
public enum SecondElementType 
{ 
    secondElement, 
    [XmlEnum("http://example.com/ns:secondElement")] 
    nsSecondElement, 
} 
당신이 실제가 XML을 설명하기 위해 xsd을 제공 한 경우

1 다음 나는 그것을 사용하기보다는 새로운 쓰기 좋을 것 :


내가 그것을 단순화 것입니다 처음부터. xsd을 성공적으로 실행할 수 있으려면 내가 제공 한 것이 실제적으로 최소값입니다. 어쨌든 XML은 XML, 네임 스페이스, 스키마 등을 이해하지 못하는 사람들이 XML을 더 많이 생성하고 있기 때문에 의심 스럽습니다.