2009-10-09 3 views
5

"thes"요소에서 "dc"네임 스페이스를 사용하는 Zthes format 디시리얼라이저 (System.Xml.Serialization)에 마무리 작업을하고 있습니다. 모든 "용어"요소는 네임 스페이스가 없기 때문에 비 직렬화입니다. 그러나 디시리얼라이저에 "thes"요소에 네임 스페이스가 있음을 알리는 방법을 알 수 없습니다.C# (System.Xml.Serialization)에서 XML 네임 스페이스를 비 직렬화하려면 어떻게해야합니까?

여기는 내가 (노력하고 있지 않은) 노력하고 있으므로 잘하면 누군가가 내게 적절한 구문을 줄 수 있습니다.

[XmlElement("namespace:someElement")] 
public string SomeElement; 

답변

8

여기에이 코드 조각이 정말 도움이

[XmlRoot("myObject")] 
public class MyObject 
{ 
    [XmlElement("myProp", Namespace = "http://www.whited.us")] 
    public string MyProp { get; set; } 

    [XmlAttribute("myOther", Namespace = "http://www.whited.us")] 
    public string MyOther { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var xnames = new XmlSerializerNamespaces(); 
     xnames.Add("w", "http://www.whited.us"); 
     var xser = new XmlSerializer(typeof(MyObject)); 
     using (var ms = new MemoryStream()) 
     { 
      var myObj = new MyObject() 
      { 
       MyProp = "Hello", 
       MyOther = "World" 
      }; 
      xser.Serialize(ms, myObj, xnames); 
      var res = Encoding.ASCII.GetString(ms.ToArray()); 
      /* 
       <?xml version="1.0"?> 
       <myObject xmlns:w="http://www.whited.us" w:myOther="World"> 
        <w:myProp>Hello</w:myProp> 
       </myObject> 
      */ 
     } 
    } 
} 
+0

... 당신을 위해 빠른 샘플입니다. Matthew에게 감사드립니다. – Junto

+0

기꺼이 도와 드리겠습니다! –

+0

OP의 질문은 직렬화가 아닌 비 직렬화에 관한 것입니다. deserialize 메서드는 XmlSerializerNamespaces 매개 변수를 사용하지 않습니다. –

1
[XmlElement("someElement", Namespace="namespace")] 
public string SomeElement; 

부록 : 확인 "네임 스페이스"를 확인 네임 스페이스의 전체 URI 아닌 접두사입니다.

관련 문제