현재 LINQ to XML을 사용하여 요소의 값을 검색하기 위해 만든 다음 확장 메서드를 사용하고 있습니다. Any()
을 사용하여 주어진 이름의 요소가 있는지 확인하고,있는 경우 값을 가져옵니다. 그렇지 않으면 빈 문자열을 반환합니다. 이 방법의 주된 용도는 XML을 C# 개체로 구문 분석 할 때 사용하기위한 것이므로 요소가 없을 때 아무 것도 나타나지 않습니다.LINQ to XML의 XML 요소를 더 빨리 검사 할 수 있습니까?
bool, int 및 double과 같은 다른 데이터 형식 및 사용자 지정 문자열을 열거 형이나 bool로 구문 분석하기위한 일부 사용자 지정 메서드가 있습니다. 또한 속성을 사용하여 작업하는 것과 동일한 메소드가 있습니다.
더 좋은 방법이 있나요?
/// <summary>
/// If the parent element contains a element of the specified name, it returns the value of that element.
/// </summary>
/// <param name="x">The parent element.</param>
/// <param name="elementName">The name of the child element to check for.</param>
/// <returns>The value of the child element if it exists, or an empty string if it doesn't.</returns>
public static string GetStringFromChildElement(this XElement x, string elementName)
{
return x.Elements(elementName).Any() ? x.Element(elementName).Value : string.Empty;
}
그래서 값을 반환 할 문자열에 XML 요소를 캐스팅 한 것으로 추측하고 있습니까? –
또한 string.Empty 대신 ""을 선택한 이유가 있습니까? –
요소를 문자열로 형변환하면 값이 반환됩니다. –