2012-08-23 75 views
1

问题是类似于:如何在.NET中声明属性的命名空间前缀?

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>

,我无法找到一个办法把前缀属性“年龄”。

如何改变上述链接中提出的解决方案才能达到目标?我尝试了不同的解决方案而没有成功

Thx in advace。

洛伦佐。

+1

你认为人们是没有年龄的,但是有名字的人有年龄?有趣... –

+0

@Damien_The_Unbeliever哈哈!!你是对的,但可能是他给了符合他要求的伪XML。 – PawanS

回答

0

您应该可以执行与链接示例中相同的操作(但使用XmlAttributeAttribute而不是XmlElementAttribute)。你的财产申报会是这样的:

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

进一步的细节和示例XmlAttributeAttribute都在msdn site

要获取fName元素上的属性,我认为您需要将年龄作为名字属性的属性。该属性应该在fName元素上还是在person元素上?

+0

我试图插入命名空间,但结果是一样的。属性上没有前缀。 – user1619644

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; 
    } 
} 
+0

Thx为答案,但您的代码生成以下xml: <?xml version =“1.0”encoding =“utf-8”?> <一:FNAME年龄=” 16.5" >约翰 韦恩 和不幸的是 “时代” 仍然不包含前缀。 – user1619644

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; } 

注:两个命名空间必须匹配。

相关问题