다음과 같은 XSD에서 유형을 생성했습니다.
[XmlType(Namespace = "http://example.com")]
public class Foo
{
public string Bar { get; set; }
}
다음과 같이 직렬화되면 :
var stream = new MemoryStream();
new XmlSerializer(typeof(Foo)).Serialize(stream, new Foo() { Bar = "hello" });
var xml = Encoding.UTF8.GetString(stream.ToArray());
출력은 다음과 같습니다.
<?xml version="1.0"?>
<Foo xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Bar xmlns="http://example.com">hello</Bar>
</Foo>
루트 요소에 네임 스페이스가 설정되지 않은 이유는 무엇입니까? 물론 다음과 같이 강제 할 수 있습니다.
var stream = new MemoryStream();
var defaultNamespace = ((XmlTypeAttribute)Attribute.GetCustomAttribute(typeof(Foo), typeof(XmlTypeAttribute))).Namespace;
new XmlSerializer(typeof(Foo), defaultNamespace).Serialize(stream, new Foo() { Bar = "hello" });
var xml = Encoding.UTF8.GetString(stream.ToArray());
출력은 다음과 같습니다.
<?xml version="1.0"?>
<Foo xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://example.com">
<Bar>hello</Bar>
</Foo>
그러나 추가 단계를 수행해야하는 것은 나에게 적합하지 않습니다. 역 직렬화 할 때 유사한 코드가 필요합니다. 속성에 문제가 있습니까? 아니면 작동 방식이며 추가 단계를 수행 할 것으로 예상됩니까?
[XmlType]
루트 요소의 이름이나 네임 스페이스를 설정하지 않습니다. 배치되는 클래스 의 유형 을 설정합니다 .
루트 요소의 이름을 설정하려면 [XmlRoot]
.
[XmlRoot(Name="FooElement", Namespace = "http://example.com")] // NS for root element
[XmlType(Name="FooType", Namespace = "http://example.com/foo")] // NS for the type itself
public class Foo
{
public string Bar { get; set; }
}
에서 설정 한 이름과 네임 스페이스 [XmlType]
는 직렬화 된 유형에 대한 XML 스키마에서, 아마도 complexType
선언에서 볼 수 있습니다. xsi:type
필요한 경우 속성 에서도 볼 수 있습니다 .
위의 선언은 XML을 생성합니다.
<ns1:FooElement xmlns:ns1="http://example.com">
XSD로
<xsd:element name="FooElement" type="ns2:FooType" xmlns:ns2="http://example.com/foo"/>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다