如何在.NET中声明属性的名称空间前缀?

时间:2012-08-23 12:13:24

标签: c# xml

问题与此类似:

How do I specify XML serialization attributes to support namespace prefixes during deserialization in .NET?

但特别针对属性。 我有类似的东西:

<person xmlns:a="http://example.com" xmlns:b="http://sample.net"> <a:fName a:age="37">John</a:fName> <b:lName>Wayne</b:lName> </person>

我无法找到将前缀添加到属性“age”的方法。

如何更改上述链接中提出的解决方案以达到目标?我尝试了不同的解决方案但没有成功。

3 个答案:

答案 0 :(得分:0)

您应该能够在链接示例中执行相同操作(但使用XmlAttributeAttribute而不是XmlElementAttribute)。您的财产声明类似于:

[XmlAttribute(Namespace = "http://example.com")]
public decimal Age { get; set; }

XmlAttributeAttribute的更多详细信息和示例位于msdn site

要获取fName元素的属性,我认为您需要将age作为first name属性的属性。属性应该在fName元素上还是在person元素上?

答案 1 :(得分:0)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml.Serialization;

    namespace XMLSer
    {
        class Program
        {
            static void Main(string[] args)
            {
                FName fname = new FName { Age = 16.5, Text = "John" };

            Person person = new Person();

            person.fname = fname;
            person.lname = "Wayne";

            XmlSerializer ser = new XmlSerializer(typeof(Person));
            ser.Serialize(Console.Out, person);
            Console.ReadKey();
        }
    }

    [XmlRoot(ElementName = "person")]
    public class Person
    {
        [XmlElement(Namespace = "http://example.com")]
        public FName fname;

        [XmlElement(Namespace = "http://sample.com")]
        public string lname;

        [XmlNamespaceDeclarations]
        public XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();

        public Person()
        {
            xmlns.Add("a", "http://example.com");
            xmlns.Add("b", "http://sample.com");
        }
    }

    public class FName
    {
        [XmlAttribute("age")]
        public double Age;

        [XmlText]
        public string Text;
    }
}

答案 2 :(得分:0)

我在尝试将“xsi:schemaLocation”指定为属性时遇到了同样的问题。

我修理了下一步:

[XmlElement("xsi", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Xsi { get; set; }    

[XmlAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string SchemaLocation { get; set; }

注意:两个NameSpace都必须匹配。

相关问题