你能简化XML数组吗?

时间:2016-07-28 19:38:39

标签: arrays xml

我想创建一个XML"数据库"目前看起来像这样:

<?xml version="1.0"?>
<ArrayOfSport xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <sport name="football">
    <countries>
      <country name="england">
        <leagues>
          <league name="premierleague">
            <teams>
              <team key="man" value="Manchester United" />
              <team key="arse" value="Arsenal" />
              <team key="bour" value="Bournemouth" />
            </teams>
          </league>
        </leagues>
      </country>
    </countries>
  </sport>
</ArrayOfSport>

如您所见,此XML可能非常混乱。所以,我的问题是,你能简化上面例子中的XML数组(<countries><leagues><teams>)吗?

<?xml version="1.0"?>
<ArrayOfSport xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <sport name="football">
    <country name="england">
      <league name="premierleague">
        <team key="man" value="Manchester United" />
        <team key="arse" value="Arsenal" />
        <team key="bour" value="Bournemouth" />
      </league>
    </country>
  </sport>
</ArrayOfSport>

或者我错过了什么?

1 个答案:

答案 0 :(得分:0)

使用XDocument修正了它。

这是生成有效XML的C#代码:

var sports =
    new XElement("sports",
        new XElement("sport", new XAttribute("name", "football"),
            new XElement("country", new XAttribute("name", "england"),
                new XElement("league", new XAttribute("name", "premierleague"),
                    new XElement("team", new XAttribute("key", "man"), new XAttribute("value", "Manchester United")),
                    new XElement("team", new XAttribute("key", "arse"), new XAttribute("value", "Arsenal")),
                    new XElement("team", new XAttribute("key", "bour"), new XAttribute("value", "Bournemouth"))
                )
            )
        )
    );

using (var fileStream = new FileStream(@"C:\XElementTest.xml", FileMode.Create))
using (var writer = new StreamWriter(fileStream))
{
    writer.Write(sports);
}

它生成了这个XML:

<sports>
  <sport name="football">
    <country name="england">
      <league name="premierleague">
        <team key="man" value="Manchester United" />
        <team key="arse" value="Arsenal" />
        <team key="bour" value="Bournemouth" />
      </league>
    </country>
  </sport>
</sports>