我在Visual Studio中有一个程序,它在XML文件中提供输出。它看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<leaCEDS>
<district>
<leaID>01</leaID>
<name>Alachua</name>
<organizationType>LEA</organizationType>
<streetLine1>620 E University Ave</streetLine1>
<city>Gainesville</city>
<stateProvince>FL</stateProvince>
<postalCode>326015448</postalCode>
<county>Alachua</county>
<NCESID_district>1200030</NCESID_district>
<date_created>2015-06-01T20:38:58.9730000</date_created>
<date_updated>2015-06-01T20:38:58.9730000</date_updated>
</district>
</leaCEDS>
我现在被告知我需要以这种格式保存XML文件的输出..
<leaCEDS xlmns="http://specification.sifassociation.org/Implementation/na/3.2/html/CEDS/K12/K12_leaCEDS.html#LinkD">
<districtEntry>
<identification>
<leaId>0001</leaId>
<name>Alachua County Public Schools</name>
<organizationType>LEA</organizationType>
</identification>
<addressList>
<address>
<street>
<line1>620 East University Avenue</line1>
<line2></line2>
</street>
<city>Gainsville</city>
<stateProvince>FL</stateProvince>
<postalCode>32601-5448</postalCode>
<county>Alachua</county>
</address>
</addressList>
<district>
<reference>
<NCESID>1200030</NCESID>
</reference>
</district>
</districtEntry>
<leaCEDS>
我该怎么做?我试过找一些解决方案,但还没找到任何东西。也许解决方案是使用XSLT?老实说,我不相信我所要求的是正确的XML文件格式,但这是我必须做的事情。
以下是我的程序的说明。
答案 0 :(得分:1)
听起来您的XML直接来自您的数据库,这意味着您需要根据您目前的结构将其转换为其他内容。
虽然您可以学习XSLT,但您也可以使用LINQ to XML执行此操作,查询已解析的文档以获取新格式所需的内容。例如:
var d = doc.Descendants("district").Single();
XNamespace ns = "http://specification.sifassociation.org/Implementation/na/3.2/html/CEDS/K12/K12_leaCEDS.html#LinkD";
var transform = new XDocument(
new XElement(ns + "leaCDS",
new XElement(ns + "districtEntry",
new XElement(ns + "identification",
new XElement(ns + "leaID", (string)d.Element("leaID")),
new XElement(ns + "name", (string)d.Element("name")),
new XElement(ns + "organizationType", (string)d.Element("organizationType"))
),
new XElement(ns + "addressList",
new XElement(ns + "address",
new XElement(ns + "street",
new XElement(ns + "line1", (string)d.Element("streetLine1")),
new XElement(ns + "line2")
),
new XElement(ns + "city", (string)d.Element("city")),
new XElement(ns + "stateProvince", (string)d.Element("stateProvince")),
new XElement(ns + "postalCode", (string)d.Element("postalCode")),
new XElement(ns + "county", (string)d.Element("county"))
)
),
new XElement(ns + "district",
new XElement(ns + "reference",
new XElement(ns + "NCESID", (string)d.Element("NCESID_district"))
)
)
)
)
);
transform.Save(writer);
请参阅此处的工作示例:https://dotnetfiddle.net/ZM27LX