开发者

Removing xmlns attribute with xml serializer

I am trying to add a prefix to one of the attributes in the element so I can give it to a program to parse, however, when I try to add a namespace it generates an additional attribute which the program does not like. I was wondering if it is possible to get rid of the additional attribute while keeping prefix for my other attribute.

Thank you.

public class Test
{
    public Test()
    {
        Namespaces=new XmlSerializerNamespaces();
        Namespaces.Add("prefix", "prefix");
    }

    [XmlNamespaceDeclarations] public XmlSerializerNamespaces Namespaces;

    [XmlAttribute(AttributeName = @"myAttribute", Namespace = @"prefix",Form = XmlSchemaForm.Qualified)]
    public string MyAttribute { get; set; }
}

What I get is this:

<Test xmlns:prefix="prefix" prefix:myAttribute="Go" />开发者_开发知识库;

What I am trying to get is:

<Test prefix:myAttribute="Go" />


No. As marc_s says, you cannot use a prefix on its own. The whole point of the prefix is to identify an XML namespace that you've already defined.

Typically (but it's not mandatory) a document will define the relationship between its prefixes and its namespaces in the root element, and then use the prefixes to reference that namespace throughout the document.

Your document:

<?xml version="1.0" encoding="UTF-8"?>
<Test prefix:myAttribute="Go" />

...is not well-formed XML, as you're saying, "this is a Test element, and it has an attribute called myAttribute in the namespace defined by the prefix prefix", but you've not defined that namespace anywhere.

This would be well-formed:

<?xml version="1.0" encoding="UTF-8"?>
<Test xmlns:prefix="prefix" prefix:myAttribute="Go" />

...as would this, which might help you, as it at least produces an element in the format you want:

<?xml version="1.0" encoding="UTF-8"?>
<SomeRootElement xmlns:prefix="prefix">
    <Test prefix:myAttribute="Go" />
</SomeRootElement>

But without an actual xmlns definition for prefix, prefix:myAttribute doesn't make sense.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜