0

I am trying to solve a puzzle with xml attributes. The problem is that we already have widely used file with this structure, from which I can't deviate

<CONFIGS>
  <CONFIG>
    <NAME>c1</NAME>
    <DB>
      <VAL1>v1</VAL1>
      <VAL2>v2</VAL2>
      <VAL3>v3</VAL3>
    </DB>
  </CONFIG>
  <CONFIG>
    <NAME>c2</NAME>
    <DB>
      <VAL1>v1</VAL1>
      <VAL2>v2</VAL2>
      <VAL3>v3</VAL3>
    </DB>
  </CONFIG>
</CONFIGS>

I've created this c# code

// master class
[XmlRoot(ElementName = "CONFIGS")]
public class MyConfigs
{

    [XmlArrayItem(ElementName = "CONFIG", Type = typeof(MyConfigSchema))]
    public MyConfigSchema[] Schemas { get; set; }
}

// I should have array of these
public class MyConfigSchema
{

    [XmlElement(DataType = "string", ElementName = "NAME")]
    public string Name { get; set; }

    [XmlElement(ElementName = "DB", Type = typeof(Db))]
    public Db Config { get; set; }

    // this element is single and has subelements
    public class Db
    {

        [XmlElement(DataType = "string", ElementName = "VAL1")]
        public string Val1 { get; set; }

        [XmlElement(DataType = "int", ElementName = "VAL2")]
        public int Val2 { get; set; }

        [XmlElement(DataType = "string", ElementName = "VAL3")]
        public string Val3 { get; set; }

    }
}

// Writing 
using (var writer = new FileStream(testfile, FileMode.Create))
        {
            var ser = new XmlSerializer(typeof(MyConfigs));
            ser.Serialize(writer, confFileObj);
            writer.Close();
        }

Here is my issue - it writes the following output, which is almost what I need but in there it writes <Schemas>. . . </Schemas> that I can't have.

<CONFIGS> --<Schemas>-- <CONFIG> <NAME>c1</NAME> <DB> <VAL1>v1</VAL1> <VAL2>v2</VAL2> <VAL3>v3</VAL3> </DB> </CONFIG> <CONFIG> <NAME>c2</NAME> <DB> <VAL1>v1</VAL1> <VAL2>v2</VAL2> <VAL3>v3</VAL3> </DB> </CONFIG> --</Schemas>-- </CONFIGS>

Is there a way of get rid of <Schemas>. . . </Schemas>?

1 Answer 1

1

Looks like I just solved it. I have never seen this before, looked on MSDN, hence I didn't try it. But I tried instead of this

[XmlArrayItem(ElementName = "CONFIG", Type = typeof(MyConfigSchema))]
public MyConfigSchema[] Schemas { get; set; }

do this

[XmlElement(ElementName = "CONFIG", Type = typeof(MyConfigSchema))]
public MyConfigSchema[] Schemas { get; set; }

Instead of XmlArrayItem I placed XmlElement and it worked. I didn't know one can mark List or array with plain element attribute.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.