我需要从xml
下面仅提取与字段相关的元素<MyDataset>
<Data>
<Name>ABC</Name>
<Date>2014-05-02T06:52:56.4931892+05:30</Date>
<Source>Source1</Source>
<Field1>10</Field1>
<Field2>11</Field2>
</Data>
<Data>
<Name>CDE</Name>
<Date>2014-05-02T06:52:56.4931892+05:30</Date>
<Source>Source2</Source>
<Field1>4</Field1>
<Field2>5</Field2>
</Data>
<Data>
<Name>FGH</Name>
<Date>2014-05-02T06:52:56.4931892+05:30</Date>
<Source>Source1</Source>
<Field1 />
<Field2 />
</Data>
</MyDataset>
我有以下代码
XElement xelem = XElement.Load(@"D:\Nirvana\NirvanaCode\Dev\Prana\myXML.xml");
IEnumerable<XElement> symbols = xelem.Elements();
foreach (XElement symbol in symbols)
{
//Here I need to add have the following xml How can I extract it from symbol
// <Data>
// <Field1>10</Field1>
// <Field2>11</Field2>
// </Data>
}
答案 0 :(得分:0)
var path_to_xml = @"D:\Nirvana\NirvanaCode\Dev\Prana\myXML.xml";
var dataset = XElement.Load(path_to_xml);
foreach (var data in dataset.Elements())
{
data.Elements().Where(e => !e.Name.LocalName.StartsWith("Field")).Remove();
string xml = data.ToString(); // use this string or data XElement
}
这将生成以下三个xml字符串:
<Data>
<Field1>10</Field1>
<Field2>11</Field2>
</Data>
<Data>
<Field1>4</Field1>
<Field2>5</Field2>
</Data>
<Data>
<Field1 />
<Field2 />
</Data>
答案 1 :(得分:0)
var elementNamesToKeep = new[] { "Field1", "Field2" };
foreach (var symbol in xelem.Elements())
{
var stripped = new XElement(
symbol.Name,
symbol.Elements().Where(e => elementNamesToKeep.Contains(e.Name.ToString())));
}