使用 C#/.net 3.5 从 xml 元素检索属性的最佳方法
如果我们有这样的 XML:
<Data>
<Cars>
<Details>
<Dataset se-datafilter="cars" dv-datamanipulationrequired="false" dv-filtercondition="" dv-sortcolumn="" dv-gettopNrows="" />
<XmlData></XmlData>
</Details>
</Cars>
<Jeeps>
<Details>
<Dataset se-datafilter="jeeps" dv-datamanipulationrequired="false" dv-filtercondition="" dv-sortcolumn="" dv-gettopNrows="" />
<XmlData></XmlData>
</Details>
</Jeeps>
</Data>
检索 sMainTagName 的
元素中存储的所有属性值的最佳方法是什么。 sMainTagName 的值可以是“Cars”或“Jeeps”。从 UI 传递。
我现在有以下代码:
var cols = doc.XPathSelectElements("/Data/" + sMainTagName + "/Details");
string sDataFilter = String.Empty;
string sFilterCondition = String.Empty;
string sSortCol = String.Empty;
foreach (var att in cols.Elements("Dataset").Attributes())
{
switch(att.Name.ToString())
{
case "se-datafilter":
sDataFilter = att.Value;
break;
case "dv-filtercondition":
sFilterCondition = att.Value;
break;
case "dv-sortcolumn":
sSortCol = att.Value;
break;
}
}
If we have a XML like:
<Data>
<Cars>
<Details>
<Dataset se-datafilter="cars" dv-datamanipulationrequired="false" dv-filtercondition="" dv-sortcolumn="" dv-gettopNrows="" />
<XmlData></XmlData>
</Details>
</Cars>
<Jeeps>
<Details>
<Dataset se-datafilter="jeeps" dv-datamanipulationrequired="false" dv-filtercondition="" dv-sortcolumn="" dv-gettopNrows="" />
<XmlData></XmlData>
</Details>
</Jeeps>
</Data>
What is the best way to retrieve the values of all the attributes stored in <Dataset>
element for sMainTagName. sMainTagName can either have value "Cars" or "Jeeps". Passed from the UI.
I have the following code now:
var cols = doc.XPathSelectElements("/Data/" + sMainTagName + "/Details");
string sDataFilter = String.Empty;
string sFilterCondition = String.Empty;
string sSortCol = String.Empty;
foreach (var att in cols.Elements("Dataset").Attributes())
{
switch(att.Name.ToString())
{
case "se-datafilter":
sDataFilter = att.Value;
break;
case "dv-filtercondition":
sFilterCondition = att.Value;
break;
case "dv-sortcolumn":
sSortCol = att.Value;
break;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我是 Linq to Xml 的粉丝。这是一个例子:
I'm a fan of Linq to Xml. Here's an example:
返回一个从属性构建的字典怎么样?
How about returning a dictionary, build up from the attributes.
就我个人而言,我不会一开始就使用 XPath。我会做这样的事情:(
顺便说一句,我假设只有一个数据集元素。);
这利用了这样一个事实:如果属性不存在(即您在 null 引用上调用它),则从
XAttribute
进行的显式字符串转换将返回 null。Personally I wouldn't use XPath to start with. I'd do something like this:
(I'm assuming there's only one Dataset element, by the way.);
This uses the fact that the explicit string conversion from
XAttribute
will return null if the attribute doesn't exist (i.e. you're calling it on a null reference).使用以下 XPath:
//Dataset/@*
,例如:Use following XPath:
//Dataset/@*
, e.g.: