从具有特定属性的 C# 类生成 XML [英] Generate XML from C# Class with specific attributes

查看:26
本文介绍了从具有特定属性的 C# 类生成 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 c# 中遇到了一个关于类的 XML 序列化的问题:我想要的是下面格式的 XML

I am stuck with an issue regarding XML serialization of a class in c#: What i Want is the XML in the format below

<?xml version="1.0" encoding="utf-8"?>
<MyClass:Req xsi:schemaLocation="http://www.Test.com/MyClass.xsd"
            xmlns:TestClass="http://www.Test.com/MyClass" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns="http://www.Test.com/MyClass">
  <head>
    <hA>01</hA>
  </head>
  <body>
    <R1>0</R1>
    <R3 />
    <R4 />
  </body>
</MyClass:Req>

所有的 XMLNS 属性都是必需的,需要通过代码进行配置.我目前得到的输出是:

All the XMLNS attributes are required and need to be configure via the code. The output i am currently getting is:

<?xml version="1.0" encoding="utf-8"?>
<MyClass_x003A_Req xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns="http://www.Test.com/MyClass">
  <head>
    <hA>01</hA>
  </head>
  <body>
    <R1>0</R1>
    <R3 />
    <R4 />
  </body>
</MyClass_x003A_Req>

如您所见,包含 prolog 的行不正确,我需要它仅显示第一个 XML 示例中的值.冒号也被转换为 x003A,我需要它成为一个冒号.

As you can see the line containing the prolog is incorrect, i need it to show just the values in the first XML example. Also the Colon is transformed to x003A and i need this to be a COLON.

这是我目前使用的代码,请记住它只是测试代码,在生产之前要更改字段.

Here is the code i am using at the moment, bear in mind its just test code the fields are to be changed before production.

request theReq = new request();
requestHead rHead = new requestHead();
requestBody rBody = new requestBody();

rHead.hA = "01";

rBody.R1 = "0";

theReq.head = rHead;
theReq.body = rBody;

XmlSerializer serializer = new XmlSerializer(typeof(request));
TextWriter textWriter = new StreamWriter(@"Test.xml");
serializer.Serialize(textWriter, theReq);
textWriter.Close();




[XmlRoot(Namespace = "http://www.Test.com/MyClass",
    ElementName = "MyClass:Req",
    DataType = "string",
    IsNullable = true)]
public partial class request
{
    private requestHead headField;

    private requestBody bodyField;

    public request()
    {
        this.bodyField = new requestBody();
        this.headField = new requestHead();
    }

    public requestHead head
    {
        get
        {
            return this.headField;
        }
        set
        {
            this.headField = value;
        }
    }

    public requestBody body
    {
        get
        {
            return this.bodyField;
        }
        set
        {
            this.bodyField = value;
        }
    }
}

public partial class requestHead
{
    private string headAField;

    private string headBField;

    public string hA
    {
        get
        {
            return this.headAField;
        }
        set
        {
            this.headAField = value;
        }
    }

    public string hB
    {
        get
        {
            return this.headBField;
        }
        set
        {
            this.headBField = value;
        }
    }
}

public partial class requestBody
{
    private string R1Field;

    private string R2Field;

    private requestBodyR3 R3Field;

    private requestBodyR4 R4Field;

    public requestBody()
    {
        this.R4Field = new requestBodyR4();
        this.R3Field = new requestBodyR3();
    }

    public string R1
    {
        get
        {
            return this.R1Field;
        }
        set
        {
            this.R1Field = value;
        }
    }

    public string R2
    {
        get
        {
            return this.R2Field;
        }
        set
        {
            this.R2Field = value;
        }
    }

    public requestBodyR3 R3
    {
        get
        {
            return this.R3Field;
        }
        set
        {
            this.R3Field = value;
        }
    }

    public requestBodyR4 R4
    {
        get
        {
            return this.R4Field;
        }
        set
        {
            this.R4Field = value;
        }
    }
}

public partial class requestBodyR3
{

    private string R31Field;

    private string R32Field;

    public string R31
    {
        get
        {
            return this.R31Field;
        }
        set
        {
            this.R31Field = value;
        }
    }

    public string R32
    {
        get
        {
            return this.R32Field;
        }
        set
        {
            this.R32Field = value;
        }
    }
}

public partial class requestBodyR4
{
    private string R41Field;

    public string R41
    {
        get
        {
            return this.R41Field;
        }
        set
        {
            this.R41Field = value;
        }
    }
}

我知道我需要更改 XMLRoot 行才能获得所需的输出,但我不确定这里需要更改什么?

I understand that i need to change the XMLRoot line to achive the desired output but i am unsure what i need to change here?

另外,在写入文件之前,我如何强制保留 COLON 而不是将其修改为 x003A.

Also how do i force the COLON to be preserved and not modified to the x003A before its written to the file.

最后一个问题,因为我没有填充 R3 &如果没有类似于 R2 未写入文件的方式填充值,R4 有没有一种方法可以防止它们被写入 XML,我相信区别在于 R2 是字符串,而 R3 &R4 是复杂类型,使得序列化程序更难确定是否应该编写它们?

One final question since i do not populate R3 & R4 is there a way i can prevent them being written to the XML if there values are not populated similar to the way R2 is not written to the file, i believe the difference is that R2 is a string and R3 & R4 are complex types making it more difficult for the serializer to determine if they should be wrote?

在应用 Ralp 建议的更改后,文件现在看起来像:

OK after applying Ralp's suggested changes the file now looks like:

<?xml version="1.0" encoding="utf-8"?>
<MyClass:Req d1p1:schemaLocation="http://www.test.com/myclass.xsd" 
             xmlns:d1p1="http://www.w3.org/2001/XMLSchema-instance" 
             xmlns:MyClass="http://www.test.com/myclass">
  <head>
    <hA>01</hA>
  </head>
  <body>
    <R1>0</R1>
    <R3 />
    <R4 />
  </body>
</MyClass:Req>

如何更改 xsi 的 d1p1?

How can I change the d1p1 for xsi?

还有一行是 xmlns="http://www.Test.com/MyClass">,我该如何添加?

Also the one line that's missing is xmlns="http://www.Test.com/MyClass">, how do i add that in?

编辑 - 2:

多亏了 Ralp 的帮助,快到了,这里是更新的文件:

Almost there thanks to Ralp's help, here is the updated file:

<?xml version="1.0" encoding="utf-8"?>
<MyClass:Req xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://www.test.com/myclass.xsd" 
             xmlns:MyClass="http://www.test.com/myclass">
  <head>
    <hA>01</hA>
  </head>
  <body>
    <R1>0</R1>
    <R3 />
    <R4 />
  </body>
</MyClass:Req>

并更新代码:

request theReq = new request();
requestHead rHead = new requestHead();
requestBody rBody = new requestBody();

rHead.hA = "01";

rBody.R1 = "0";

theReq.head = rHead;
theReq.body = rBody;

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
ns.Add("MyClass", "http://www.test.com/myclass");

XmlSerializer serializer = new XmlSerializer(typeof(request));
TextWriter textWriter = new StreamWriter(@"Test.xml");
serializer.Serialize(textWriter, theReq, ns);
textWriter.Close();



[XmlRoot(Namespace = "http://www.test.com/myclass", ElementName = "Req")]
public partial class request
{
    private requestHead headField;

    private requestBody bodyField;

    public request()
    {
        this.bodyField = new requestBody();
        this.headField = new requestHead();
    }

    [XmlAttribute("schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string xsiSchemaLocation = "http://www.test.com/myclass.xsd";

    [XmlElement("head", Namespace = "")]
    public requestHead head
    {
        get
        {
            return this.headField;
        }
        set
        {
            this.headField = value;
        }
    }

    [XmlElement("body", Namespace = "")]
    public requestBody body
    {
        get
        {
            return this.bodyField;
        }
        set
        {
            this.bodyField = value;
        }
    }
}

public partial class requestHead
{
    private string headAField;

    private string headBField;

    public string hA
    {
        get
        {
            return this.headAField;
        }
        set
        {
            this.headAField = value;
        }
    }

    public string hB
    {
        get
        {
            return this.headBField;
        }
        set
        {
            this.headBField = value;
        }
    }
}

public partial class requestBody
{
    private string R1Field;

    private string R2Field;

    private requestBodyR3 R3Field;

    private requestBodyR4 R4Field;

    public requestBody()
    {
        this.R4Field = new requestBodyR4();
        this.R3Field = new requestBodyR3();
    }

    public string R1
    {
        get
        {
            return this.R1Field;
        }
        set
        {
            this.R1Field = value;
        }
    }

    public bool ShouldSerializeR1() { return !String.IsNullOrEmpty(R1); }

    public string R2
    {
        get
        {
            return this.R2Field;
        }
        set
        {
            this.R2Field = value;
        }
    }

    public bool ShouldSerializeR2() { return !String.IsNullOrEmpty(R2); }

    public requestBodyR3 R3
    {
        get
        {
            return this.R3Field;
        }
        set
        {
            this.R3Field = value;
        }
    }

    public bool ShouldSerializeR3() { return requestBodyR3.ShouldSerializeRequestBodyR3(); }

    public requestBodyR4 R4
    {
        get
        {
            return this.R4Field;
        }
        set
        {
            this.R4Field = value;
        }
    }
}

public partial class requestBodyR3
{

    private string R31Field;

    private string R32Field;

    public static bool ShouldSerializeRequestBodyR3()
    {
        bool blnRetVal = false;

        //Add code to test these values later

        return blnRetVal;
    }

    public string R31
    {
        get
        {
            return this.R31Field;
        }
        set
        {
            this.R31Field = value;
        }
    }

    public string R32
    {
        get
        {
            return this.R32Field;
        }
        set
        {
            this.R32Field = value;
        }
    }
}

public partial class requestBodyR4
{
    private string R41Field;

    public string R41
    {
        get
        {
            return this.R41Field;
        }
        set
        {
            this.R41Field = value;
        }
    }
}

现在唯一的问题是缺少 xmlns="http://www.Test.com/MyClass">

The only problem now is the lack of the line xmlns="http://www.Test.com/MyClass">

如果我将以下代码添加到命名空间部分:

If i add the following code to the namespace section:

ns.Add("", "http://www.test.com/Myclass");

我得到了我需要的输出,但 NOTICEi jhad 更改其中一个字母的大小写以获取输出,如果大小写与命名空间 MyClass 相同,则它不会输出.

I get the output i require but NOTICEi jhad to change the case on one of the letters to get the output if the case is the same as the namespace MyClass then it does not output.

提前致谢

推荐答案

Namespace 是 MyClass,Elementname 是 Req.所以你需要定义命名空间.

The Namespace is MyClass and the Elementname is Req. So you need to define the Namespace.

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();            
ns.Add("MyClass", "http://www.test.com/myclass");

并调用采用 XmlSerializerNamespaces 实例的 Serialize 重载.Request 类本身就是一个名为 Req 的元素.

and call a Serialize overload that takes an XmlSerializerNamespaces instance. The Request class itself is then an Element named Req.

[XmlRoot(Namespace = "http://www.test.com/myclass", ElementName = "Req")]
public class Request
{
    [XmlElement("R1", Namespace = "")]
    public string R1 { get; set; }
    public bool ShouldSerializeR1()  { return !string.IsNullOrWhiteSpace(R1); }

    [XmlAttribute("schemaLocation", Namespace = "")]
    public string xsiSchemaLocation = "http://www.test.com/myclass.xsd";
}

schemaLocation 可以通过声明为 Xml 属性的属性添加.一个属性是否应该被序列化可以通过一个方法控制,使用 ShouldSerialize*MyLovelyPropertyName()* 语法.

schemaLocation can be added via a Property declared as a Xml Attribute. If a property should be serialize can be controlled by a method with a ShouldSerialize*MyLovelyPropertyName()* syntax.

这篇关于从具有特定属性的 C# 类生成 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆