실제 XML에는 하나의 루트 요소 만 있습니다. 'Response', 'Count', 'Message', 'SearchCriteria'및 'Results'가 루트 요소로 있습니다. 또한 '응답'태그를 닫아야합니다. 다음과 같습니다
나무 상자 구조 :
<?xml version="1.0"?>
<Content>
<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Count>116</Count>
...
</Content>
그런 다음 System.Xml.Linq.XDocument.Parse()
또는 XDocument.Load()
로 XML을로드 할 수 있습니다.
다음은 찾고자하는 가치에 도달하는 예입니다.
//Load XML
XDocument document = XDocument.Parse("<?xml version=\"1.0\"?><Content><Count>116</Count><Message>Results returned successfully</Message><SearchCriteria>VIN:KM8JM12B66U253804</SearchCriteria><Results> <DecodedVariable> <VariableId>10</VariableId> <Variable>Destination Market</Variable> </DecodedVariable> <DecodedVariable> <VariableId>26</VariableId> <Variable>Make</Variable> <ValueId>498</ValueId> <Value>HYUNDAI</Value> </DecodedVariable> <DecodedVariable> <VariableId>27</VariableId> <Variable>Manufacturer Name</Variable> <ValueId>1034</ValueId> <Value>HYUNDAI-KIA AMERICA TECHNICAL CENTER INC (HATCI)</Value> </DecodedVariable> <DecodedVariable> <VariableId>28</VariableId> <Variable>Model</Variable> <ValueId>2058</ValueId> <Value>Tucson</Value> </DecodedVariable> <DecodedVariable> <VariableId>29</VariableId> <Variable>Model Year</Variable> <ValueId/> <Value>2006</Value> </DecodedVariable></Results></Content>");
//Select root Element
var root = document?.Root;
//Go down to the 'Results' element. There is just a single element so use 'Element()'
var results = root?.Element("Results");
//Get every 'DecodedVariable'. There are multiple elements so use 'Elements()'
var decodedVariables = results?.Elements("DecodedVariable");
//Select the only element with 'VariableId'==26 or null if no element maches
var value = decodedVariables?.SingleOrDefault((decodedVariable) =>
//Do the following for every element 'DecodedVariable'
{
//Try parse the 'VariableId' as int
if (int.TryParse(decodedVariable?.Element("VariableId")?.Value, out int id))
//Compare the value of 'VariableId' with the value you're looking for. In this case 26
if (id == 26)
//This is the correct 'DecodedVariable' element
return true;
//This is not the correct 'DecodedVariable' element
return false;
})
//Get the element 'Value' from the element 'DecodedVariable' then get the value from the element 'Value'
?.Element("Value")?.Value;
//'HYUNDAI' is stored in 'value'
Console.WriteLine(value);
어디서나 null이 예상됩니다. XElement.Elements()
은 일치하는 요소를 찾을 수없는 경우 null을 반환합니다. 그래서 ?.
을 사용했습니다. 미리 스키마에 대해 유효성을 검사하는 경우 필요하지 않을 수 있습니다. 비록 당신이 이것을하지 않거나 xml이 유효하지 않다는 것을 깨달았을지라도.
'VariableId'를 int로 구문 분석 할 필요가 없습니다. 문자열을 == 26.ToString()
으로 비교할 수도 있습니다.
몇 군데에서 null을 확인하는 것을 잊었을 것입니다. 코드를 직접 사용하기 전에 확인하십시오.