1

윈도우 폰 7 응용 프로그램을 개발 중입니다. 내 응용 프로그램의 데이터베이스로 XML을 사용하고 있습니다. 내 응용 프로그램에 데이터베이스 테이블 대신 XML 파일을 사용하고 있습니다. 내 XML 파일 중 하나에 대해 다음 구조를 가지고 있습니다. 위의 XML 파일에서 LINQ to XML을 사용하여 첫 번째 레코드의 XML 파일에 ID를 쓰는 방법은 무엇입니까?

<?xml version="1.0" encoding="utf-8" ?> 
<Categories> 
    <Category> 
    <Category_ID></Category_ID> 
    <Category_Name></Category_Name> 
    <TransactionType_ID></TransactionType_ID> 
    </Category> 
    <Category> 
    <Category_ID></Category_ID> 
    <Category_Name></Category_Name> 
    <TransactionType_ID></TransactionType_ID> 
    </Category> 
</Categories> 

나는 XML에 LINQ를 사용하여 내 모바일 애플리케이션의 사용자 인터페이스를 통해 CATEGORY_NAME & TransactionType_ID의 값을 삽입하고있다. 위 XML 파일에서 Category_ID를 기본 키 & TransactionType_ID를 다른 xml 파일에 속하는 외래 키로 간주합니다. 위 XML 파일에서 우리는 데이터베이스 테이블에서와 마찬가지로 노드 Category_ID에 대한 자동 증가 ID를 생성하려고합니다. 이를 위해 다음 코드

private int new_record_id() 
     { 
      IsolatedStorageFile isstore = IsolatedStorageFile.GetUserStoreForApplication(); 
      IsolatedStorageFileStream bookfile = new IsolatedStorageFileStream("Categories.xml", System.IO.FileMode.Open, isstore); 

      XDocument xmldetails = XDocument.Load(bookfile);   

      var details = (from detail in xmldetails.Descendants("Category") 
          select (int.Parse(detail.Element("Category_ID").Value))).Max(); 


      bookfile.Close(); 

      return details + 1; 
     } 

을 사용하고 있습니다하지만 XML 파일에서 첫 번째 레코드를 삽입 할 때 처음에 내 XML 파일에 대한 기록이 없기 때문에 그것은 다음 문장에 오류가 있습니다.

var details = (from detail in xmldetails.Descendants("Category") 
           select (int.Parse(detail.Element("Category_ID").Value))).Max(); 

XML 파일의 첫 번째 레코드를 삽입 할 수있는 코드 나 링크 또는 솔루션을 제공해 주시겠습니까? 내가 틀린 일을하고 있다면 나를 안내 해주십시오.

var id = xmlDetails.Descendants("book") 
        .Max(x => (int) x.Element("id")); 

지금 당신이 당신의 XML에 어떤 책이없는 경우 경우를 처리 할 수 ​​있도록하려면 나는, : 조회로 훨씬 더 간단하게 쓸 수와

답변

1

음, 시작 '이 명시 적으로 첫 번째 테스트를 D :

int id; 
if (xmlDetails.Descendants("book").Any()) 
{ 
    id = xmlDetails.Descendants("book") 
        .Max(x => (int) x.Element("id")); 
} 
else 
{ 
    id = -1; // Or whatever you want to do 
} 

(당신이 원하는 경우도 이것에 대한 조건 연산자를 사용할 수 있습니다.)

관련 문제