我使用以下代码从OData XML及其工作中获取数据, 但我不确定我是否完全理解它,所以也许有一种方法可以用简单的方式编写它? 我需要的是获取第一个循环值= 0001和text = approve的属性值 第二个值= 0002 text = reject
代码
XNamespace dns = "http://schemas.microsoft.com/ado/2007/08/dataservices";
if (response.StatusCode == HttpStatusCode.OK)
{
string decisionOptions = ReadResponse(response);
XDocument document = XDocument.Parse(decisionOptions);
foreach (XElement element in document.Element(dns + "DecisionOptions").Elements(dns + "element"))
{
PropertyKeyRef decisionOption = new PropertyKeyRef();
decisionOption.PropertyValue = element.Element(dns + "DecisionKey").Value;
decisionOption.PropertyName = element.Element(dns + "DecisionText").Value;
dat.Add(decisionOption);
}
}
XML
<?xml version="1.0" encoding="utf-8" ?>
- <d:DecisionOptions xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
- <d:element m:type="TAS.DecisionOption">
<d:InstanceID>007</d:InstanceID>
<d:DecisionKey>0001</d:DecisionKey>
<d:DecisionText>Approve</d:DecisionText>
<d:CommentMandatory>false</d:CommentMandatory>
<d:Nature>POSITIVE</d:Nature>
</d:element>
- <d:element m:type="TAS.DecisionOption">
<d:InstanceID>007</d:InstanceID>
<d:DecisionKey>0002</d:DecisionKey>
<d:DecisionText>Reject</d:DecisionText>
<d:CommentMandatory>true</d:CommentMandatory>
<d:Nature>NEGATIVE</d:Nature>
</d:element>
</d:DecisionOptions>
答案 0 :(得分:1)
您已经以最简单的方式实现了它。 LINQ
的一点点可能会提高可读性(远离foreach循环),但它只是你所写内容的syntactic sugar
。
XNamespace dns = "http://schemas.microsoft.com/ado/2007/08/dataservices";
XDocument document = XDocument.Load("database.xml");
PropertyKeyRef decisionOption = new PropertyKeyRef();
decisionOption.PropertyValue = document.Descendants(dns + "DecisionKey")
.Select(node => node.Value).First();
decisionOption.PropertyName = document.Descendants(dns + "DecisionText")
.Select(node => node.Value).First();
dat.Add(decisionOption);
答案 1 :(得分:1)
这里如何使用LINQ
以简单的方式完成namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
XDocument xdoc = XDocument.Load("test.xml");
XNamespace dns = "http://schemas.microsoft.com/ado/2007/08/dataservices";
//in xml every element should have it's namespace for this reason I have to concatenate namespace with the name of element
var elementsRes = xdoc.Root.Elements(dns+"element").Select((elt) => new PropertyKeyRef { PropertyName = elt.Element(dns+"DecisionKey").Value.ToString(),PropertyValue = elt.Element(dns+"DecisionText").Value.ToString() }).ToList();
foreach (var item in elementsRes)
{
//your code for the result
}
}
}
public class PropertyKeyRef
{
public string PropertyName
{ get; set; }
public string PropertyValue
{ get; set; }
}
}