我正在尝试使用xml属性解决难题。问题是我们已经广泛使用了具有这种结构的文件,我无法偏离
<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>
我已经创建了这个c#代码
// 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();
}
这是我的问题 - 它写了以下输出,这几乎是我需要的,但在那里它写了<Schemas>. . . </Schemas>
我无法做到。
<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>
有没有办法摆脱<Schemas>. . . </Schemas>
?
答案 0 :(得分:1)
看起来我刚解决了。我以前从未见过这个,看过MSDN,因此我没有尝试过。但我试过而不是这个
[XmlElement(ElementName = "CONFIG", Type = typeof(MyConfigSchema))]
public MyConfigSchema[] Schemas { get; set; }
这样做
XmlArrayItem
而不是XmlElement
我放置#include <string>
#include <sstream>
#include <vector>
#include <cctype>
#include <locale>
#include <iterator>
#include <algorithm>
#include <functional>
struct my_punct : std::numpunct<char> {
protected:
virtual char do_decimal_point() const { return ','; }
virtual std::string do_grouping() const { return "\000"; } // groups of 0 (disable)
};
struct sName {
std::string value;
};
static inline void rtrim(std::string &s) {
s.erase(
std::find_if(
s.rbegin(), s.rend(),
std::not1(std::ptr_fun<int, int>(std::isspace))
).base(),
s.end()
);
}
std::istream& operator>>(std::istream &in, sName &out)
{
char ch, last = 0;
std::ostringstream oss;
std::istream::sentry s(in);
if (s)
{
out.value.erase();
do
{
ch = in.peek();
if (!in) break;
if (std::isspace(last) && std::isdigit(ch)) break;
ch = in.get();
oss << ch;
last = ch;
}
while (true);
out.value = oss.str();
rtrim(out.value);
}
return in;
}
并且它有效。我不知道可以用普通元素属性标记List或数组。