当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - ArrayIndex in XMLAttribute

问题描述:

I have an Xml which should be formatted like:

<name Segment1="infofor1" segment2="infofor2" Segment1_OtherInfo="SomethingElseFor1" Segment2_OtherInfo="SomethingElseFor2"/>

For the class I thought about the fallowing:

public class Name{

public Segment[]Segment{get;set;}

}

public class Segment{

[XmlAttribute("Segment???")]

public string Segment{get;set;}

[XmlAttribute("Segment???_OtherInfo")]

public string SegmentOtherInfo{get;set;}

}

Generally speaking I want the index of the array into my Name of the XML Attribute. I Think that is totally nasty, but I cant change the xml, it is a requirement.

How can I achive that. The class I can change how I want.

Nice would be that the attributes are not written if they are empty.

网友答案:

I believe that the annotations in brackets will not be flexible enough for this (but I'd have to spend more time to find out). They rely on reflection and the XMLSeralizer, which means your code should represent somehow the XML model.

In my opinion, it is easier just to create XElements and XAttributes. With them, you can loop through your arrays, get the array's index (or to increase a counter) and add the necessary attributes with a suitable name.

Here is a well written example: http://csharp-guide.blogspot.ch/2012/06/xattribute-class-is-used-along-with.html

Like this:

...
new XElement("name", new XAttribute("Segment" + counter, "infofor" + counter));
...
分享给朋友:
您可能感兴趣的文章:
随机阅读: