itsource

에서 출력의 공백 xmlns 특성을 방지하는 방법.NET의 Xml 문서?

mycopycode 2023. 9. 19. 21:03
반응형

에서 출력의 공백 xmlns 특성을 방지하는 방법.NET의 Xml 문서?

의 XmlDocument에서 XML을 생성할 때.NET, 백지xmlns연관된 네임스페이스가 없는 요소를 처음 삽입할 때 attribute가 나타납니다. 이를 방지하려면 어떻게 해야 합니까?

예:

XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root",
    "whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner"));
Console.WriteLine(xml.OuterXml);

출력:

<root xmlns="whatever:name-space-1.0"><loner xmlns="" /></root>

원하는 출력:

<root xmlns="whatever:name-space-1.0"><loner /></root>

에 적용할 수 있는 해결책이 있습니까?XmlDocument코드, 문서를 문자열로 변환한 에 발생하는 것이 아닙니다.OuterXml?

이것을 하는 나의 이유는 XmlDocument 생성 XML을 사용하여 특정 프로토콜의 표준 XML과 일치할 수 있는지 확인하기 위함입니다. 빈칸xmlns속성은 파서가 깨지거나 혼란스럽지 않을 도 있지만, 이 프로토콜을 본 어떤 용도로도 존재하지 않습니다.

제레미 루의 대답과 조금 더 장난친 덕분에, 저는 빈칸을 없애는 방법을 알아냈습니다.xmlns속성: 접두사를 사용하지 않으려는 자식 노드를 만들 때 루트 노드의 네임스페이스에 전달합니다.루트에 접두사가 없는 네임스페이스를 사용하면 하위 요소에 동일한 네임스페이스를 사용해야 접두사가 없습니다.

고정 코드:

XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner", "whatever:name-space-1.0")); 
Console.WriteLine(xml.OuterXml);

저를 올바른 방향으로 인도해주신 모든 답변에 모두 감사드립니다!

이것은 JeniT의 답변을 변형한 것입니다 (그런데 정말 감사합니다!)

XmlElement new_element = doc.CreateElement("Foo", doc.DocumentElement.NamespaceURI);

따라서 네임스페이스를 모든 곳에서 복사하거나 반복할 필요가 없습니다.

만약에<loner>당신의 샘플 XML에 있는 요소는xmlns기본 네임스페이스 선언을 실행하면whatever:name-space-1.0네임스페이스가 없는 대신 네임스페이스가 있습니다.원하는 경우 해당 네임스페이스에 요소를 생성해야 합니다.

xml.CreateElement("loner", "whatever:name-space-1.0")

당신이 원한다면.<loner>요소가 네임스페이스에 없으면 생성된 XML이 정확히 필요한 것이 됩니다. 그리고 당신은 그 요소에 대해 걱정할 필요가 없습니다.xmlns자동으로 추가된 속성입니다.

루트는 미리 고정되지 않은 네임스페이스에 있으므로 네임스페이스를 지정하지 않으려는 루트의 자식은 예제와 같이 출력해야 합니다.해결책은 다음과 같이 루트 요소의 접두사를 붙이는 것입니다.

<w:root xmlns:w="whatever:name-space-1.0">
   <loner/>
</w:root>

코드:

XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement( "w", "root", "whatever:name-space-1.0" );
doc.AppendChild( root );
root.AppendChild( doc.CreateElement( "loner" ) );
Console.WriteLine(doc.OuterXml);

가능한 경우 serialization 클래스를 만든 다음 다음 작업을 수행합니다.

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer serializer = new XmlSerializer(yourType);
serializer.Serialize(xmlTextWriter, someObject, ns);

더 안전하고, 더 많은 제어가 필요한 경우 속성을 사용하여 네임스페이스를 제어할 수 있습니다.

저는 팩토리 패턴을 이용하여 문제를 해결하였습니다.XElement 객체에 대한 공장을 만들었습니다.공장 인스턴스화를 위한 매개 변수로 XNamespace 객체를 지정했습니다.따라서 공장에서 XElement를 생성할 때마다 네임스페이스가 자동으로 추가됩니다.공장 코드는 다음과 같습니다.

internal class XElementFactory
{
    private readonly XNamespace currentNs;

    public XElementFactory(XNamespace ns)
    {
        this.currentNs = ns;
    }

    internal XElement CreateXElement(String name, params object[] content)
    {
        return new XElement(currentNs + name, content);
    }
}

예, XmlElement에서 XMLNS를 방지할 수 있습니다.첫번째 시간 만들기 그것이 다가오고 있습니다 : 그렇게 말입니다.

<trkpt lat="30.53597" lon="-97.753324" xmlns="">
    <ele>249.118774</ele>
    <time>2006-05-05T14:34:44Z</time>
</trkpt>

코드를 변경합니다 : 그리고 xml 네임스페이스를 이렇게 전달합니다.

C# 코드:

XmlElement bookElement = xdoc.CreateElement("trkpt", "http://www.topografix.com/GPX/1/1");
bookElement.SetAttribute("lat", "30.53597");
bookElement.SetAttribute("lon", "97.753324");

언급URL : https://stackoverflow.com/questions/135000/how-to-prevent-blank-xmlns-attributes-in-output-from-nets-xmldocument

반응형