在R

时间:2018-01-14 13:30:01

标签: sql-server r xml

我目前正在尝试使用R代码导入.sqlplan XML文件进行处理,但我遇到了一些问题。

首先,当我在R中导入.sqlplan文件时,遇到编码问题:

library(XML)
library(readr)

xml_file_raw <- "example.sqlplan"
xml_file <- read_file(xml_file_raw) 
doc <- xmlInternalTreeParse(xml_file)

Document labelled UTF-16 but has UTF-8 content
Error: 1: Document labelled UTF-16 but has UTF-8 content

当我按照计划XML中的配置提供UTF-16编码时,我得到另一个错误:

doc <- xmlInternalTreeParse(xml_file, encoding = "UTF-16")
Start tag expected, '<' not found
Error: 1: Start tag expected, '<' not found

如果我切换到UTF-8,它可以正常工作

doc <- xmlInternalTreeParse(xml_file, encoding = "UTF-8")

但是,如果我想获得头部XML节点,我注意到整个XML都在其中(在这个问题中只添加了一小部分XML)

xmlRoot(doc)
<ShowPlanXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" Version="1.5" Build="13.0.4435.0">
  <BatchSequence>
    <Batch>
      <Statements>
        <StmtSimple StatementCompId="1" StatementEstRows.....

当我尝试从XML中检索特定参数时,我总是得到一个NULL结果:

xpathSApply(doc, "//ns:ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple/@StatementText", xmlValue, namespaces = c(ns = "http://schemas.microsoft.com/sqlserver/2004/07/showplan"))
NULL

我在这里上传了完整的.sqlplan XML文件:example.sqlplan

这个R代码的主要目标是从导出的.sqlplan文件本身检索各种执行计划变量(如SQL语句,CPU时间,内存授权等)

谢谢!

1 个答案:

答案 0 :(得分:0)

为默认命名空间分配前缀时,例如 ns ,只需将其应用于XPath的每个元素,而不仅仅是第一个节点:

library(XML)

data <- readLines("https://raw.githubusercontent.com/Evdlaar/QueryStoreReplay/master/example.sqlplan")
doc <- xmlParse(data, asText = TRUE, encoding = "UTF-8")

sql <- xpathSApply(doc, "//ns:ShowPlanXML/ns:BatchSequence/ns:Batch/ns:Statements/ns:StmtSimple/@StatementText", 
                   namespaces = c(ns = "http://schemas.microsoft.com/sqlserver/2004/07/showplan"))

cat(sql)
# Select  
#  p.EnglishProductName,
#  s.SalesAmount,
#  s.UnitPrice,
#  s.DiscountAmount
# from FactResellerSales s
# INNER JOIN DimProduct p on s.ProductKey = p.ProductKey
相关问题